Ordered bars on plotly - r

I'm trying to make a CPU Usage graph with Plotly and R, I want the max usage (100%, the blue bar) on top, and the other one on bottom, but when I try this code
plot_ly( x = cores, y = max, type = 'bar', name = 'Free') %>%
add_trace( y = data, name = 'Used') %>%
layout(
title = "CPU Usage",
font = list(family = 'Comic Sans MS'),
yaxis = list(title = 'Percent'),
xaxis = list(title = '', tickangle = -45),
barmode = 'stack')
})
It gives me the reverse, ordering the greater bar on bottom, and the orange one on top. I want to invert it.
I searched on some references but nothing was found about that...

We do not know your data but:
cores <- c("Average", "Core1", "Core2", "Core5")
Free <- c(65, 60, 80,50)
Used <- c(100-65, 40, 20,50)
data <- data.frame(cores, Free, Used)
plot_ly(data, x = ~cores, y = ~Used, type = 'bar', name = 'Used') %>%
add_trace(y = ~Free, name = 'Free') %>%
layout(yaxis = list(title = '%'), barmode = 'stack')

Related

Create a stacked bar chart with 3 traces for 2 bars

I am trying to replicate the following stacked bar chart with plotly. I attach one screenshot for every hover text I get when hovering on a bar. As you will see there are 2 issues. First I cannot achieve 3 colors, besides the fact that I create them in the legend and secondly I cannot put First dose as top bar besides the fact that I use factor() based on the levels. Maybe there is an issue with the way I have created my dataset. I have no problem if you have to reform it instead of fix the plotly code to replicate the chart.
library(plotly)
Category<-c("First dose","Full vaccination")
`Uptake first dose`<-c(19.8,7.6)
`Uptake full vaccination`<-c(0,0)
`Not vaccinated`<-c(80.2,92.4)
ch5<-data.frame(Category,`Uptake first dose`,`Uptake full vaccination`,`Not vaccinated`)
ch5$Category <- factor(ch5$Category, levels = ch5[["Category"]])
ax <- list(
title = "",
showticklabels = FALSE,
showgrid = FALSE
)
fig <- plot_ly(ch5, y = ~Category, x = ~`Uptake first dose`,
type = 'bar', name = 'Uptake first dose',marker = list(color = 'lightgreen'))
fig <- fig %>% add_trace(x = ~`Uptake full vaccination`, name = 'Uptake full vaccination',marker = list(color = 'green'))
fig <- fig %>% add_trace(x = ~`Not vaccinated`, name = 'Not vaccinated',marker = list(color = 'gray'))
fig <- fig %>% layout(yaxis = ax,xaxis=list(title="",showgrid=F), barmode = 'stack')
fig
There might be a problem with your dataset. The 7.6% of full vaccination is listed under first doese. Therefore your coloring might not work.
Furthermore I transformed the data into a long format for an easy way to create hovertemplates.
library(plotly)
library(tidyverse)
# data
Category<-c("First dose","Full vaccination")
`Uptake first dose`<-c(19.8,0)
`Uptake full vaccination`<-c(0,7.6)
`Not vaccinated`<-c(80.2,92.4)
ch5<-data.frame(Category,`Uptake first dose`,`Uptake full vaccination`,`Not vaccinated`)
# transform data
data.long <- ch5 %>%
pivot_longer(cols = -Category,
names_to = "vac",
values_to = "percent") %>%
mutate(vac = str_replace_all(vac, "\\.", " "),
vac = fct_rev(factor(vac)))
# add plot
plot_ly(data.long) %>%
add_bars(y = ~Category,
x = ~percent,
color = ~vac,
text = ~vac,
colors = c("darkgreen", "green", "gray"),
hovertemplate = paste('<b>%{y}</b>',
'<br>%{text}: %{x} ',
'<extra></extra>')) %>%
layout(barmode = "stack",
yaxis = list(autorange="reversed"),
hoverlabel = list(bgcolor = "black",
bordercolor = "black",
font = list(color = "white")),
shapes = list(type = "line",
y0 = 0, y1 = 1, yref = "paper",
x0 = 70, x1 = 70),
annotations = list(text = "Target (70.0%)",
showarrow = FALSE,
x = 70,
y = 1.05,
yref = "paper"))

Removing Unused Subplot in R Plotly

When using plotly (in R), after combining subplots there remains an unused and blank subplot. I've recreated the issue using the ggplot2 dataset mpg below.
library(dplyr)
library(ggplot2)
library(plotly)
audi <- mpg %>%
filter(manufacturer == "audi")
chevy <- mpg %>%
filter(manufacturer == "chevrolet")
fig1 <- plot_ly(audi, x = ~hwy, y = ~year, name = "", type = 'scatter',
mode = "markers", marker = list(color = "blue", symbol = 'x-dot'))
fig2 <- plot_ly(chevy, x = ~hwy, y = ~year, name = "", type = 'scatter',
mode = "markers", marker = list(color = "red", symbol = 'circle'))
fig <- subplot(fig1, fig2)
fig <- fig %>% subplot(shareX = TRUE,shareY = TRUE,which_layout = "merge")
fig <- fig %>% layout(
title = "Audi and Chevy",
xaxis = list(title = "Highway MPG"),
yaxis = list(title = "Year"),
margin = list(l = 100)
)
The only solution I've been able to find is tinkering with the width of the used subplot, but this leaves quite a bit of unused white space on the right and causes the title to be far off to the right (as it adjusts into the center of the used and unused subplots).
Is there a way to remove the unused subplot? If not, is there a way to organize/subset the dataframe such that only one plot needs to be used in the first place?
Thanks!
You can assign the colours based on the manufacturer column:
data.subs <- mpg %>%
filter(manufacturer == "audi" | manufacturer == "chevrolet")
fig <- plot_ly(data.subs, x = ~hwy, y = ~year, name = "",
type = 'scatter', mode = "markers",
marker = list(color = factor(data.subs$manufacturer,
labels = c("red", "blue")),
symbol = 'circle'),
text = factor(data.subs$manufacturer,
labels = c("audi", "chevy")), hoverinfo = 'text'))
fig <- fig %>% layout(
title = "Audi and Chevy",
xaxis = list(title = "Highway MPG"),
yaxis = list(title = "Year"),
margin = list(l = 100)
)
fig
This makes generating multiple subplots unnecessary.

How do I allow Plotly bar text to overflow past bar?

How do I get the text size for dr5 and dr3 for the shorter bars? If the text is longer than the bar span, I would like the text to overflow past the end of the bar.
I tried using uniformtext in layout, but that shrunk all text to the smallest font being used. How do I change all font to the biggest size being used?
library(plotly)
# Test long text and short bars
xValues <- c("loooooooooooooooooonnnnnngg","lonnnnnnnnnnggggggg",
"dr3","dr4","dr5")
yValues <- c(0.5,1,2,0.22,10)
bar <- plot_ly(x = yValues,
y = xValues) %>%
add_trace(
type = 'bar',
orientation = 'h',
text = xValues,
textangle = 360,
textposition = "inside",
insidetextanchor = "start",
showlegend = F) %>%
layout(
yaxis = list(zeroline = FALSE,showline = FALSE,showticklabels = FALSE),
uniformtext = list(mode = "show")
)
bar
This can be achieved by adding the labels via add_text like so:
BTW: I put the vectors inside a df. Seems more natural to me.
library(plotly)
# Test long text and short bars
xValues <- c("loooooooooooooooooonnnnnngg","lonnnnnnnnnnggggggg",
"dr3","dr4","dr5")
yValues <- c(0.5,1,2,0.22,10)
df <- data.frame(
x = xValues,
y = yValues
)
bar <- plot_ly(df, x = ~y, y = ~x, text = ~x) %>%
add_trace(
type = 'bar',
orientation = 'h',
showlegend = F) %>%
add_text(x = 0.1, textposition = "middleright") %>%
layout(yaxis = list(zeroline = FALSE,showline = FALSE, showticklabels = FALSE))
bar

Creating a line plot using plot_ly (R) with two y-axes

I am a newcomer to the plot_ly package and am trying to produce a time series line plot with two variables on the y axis.
In my dataframe 'baro' I have 'DateTime' variable in POSIXct format, and 'Pressure' and 'Temperature' in numeric format.
I am basing my code off the example given here: https://plot.ly/r/multiple-axes/
p <- plot_ly(baro)
add_trace(p, x = ~DateTime, y = ~Pressure, type = "scatter",
mode = "lines", name = "Pressure")
add_trace(p, x = ~DateTime, y = ~Temperature, type = "scatter",
mode = "lines", name = "Temperature", yaxis = "y2")
layout(p,
title = "Pressure & Temperature", yaxis2 = ay,
xaxis = list(title="x")
)
This outputs a set of axes labelled -1 to 6 on the x axis and -1 to 4 on the y axis with no data plotted.
I prefer use pipes %>% rather than attribute an object to a plot.
When you have 2 Y-axis it's nice to set the layout of every one explicitly.
This should do what you want:
# Build randon data
set.seed(123)
baro = data.frame(DateTime = as.POSIXct(1:10,origin = "2019-01-01"),
Pressure = sample(1000:2000,10),
Temperature = sample(20:60,10)
)
# Build plot
baro %>%
plot_ly(type = "scatter", mode = "lines") %>%
add_trace(x = ~DateTime, y = ~Pressure, name = "Pressure")%>%
add_trace(x = ~DateTime, y = ~Temperature, name = "Temperature", yaxis = "y2") %>%
layout(title = "Pressure & Temperature",
yaxis = list(title = "Pressure"),
yaxis2 = list(title = "Temperature",
overlaying = "y",
side = "right"
)
)
Here the output:
Best regards.

How to create an Orbit Chart in R? (Plotly/ggplot2)

I have spent time researching with no direction on how to create an orbit chart
I would ideally like to be able to create interactive versions (such as Plotly) but a ggplot2 would suffice as well.
Any suggestions are much appreciated!
For a weekly vis contest some time ago, I created some charts like this. I think the commonly accepted term now is "connected scatterplot".
Here is the skeleton plotly code I used.
plot_ly(
df,
x = x_var,
y = y_var,
group = group_var,
mode = "markers") %>%
add_trace(
x = x_var,
y = y_var,
xaxis = list(title = ""),
yaxis = list(title = ""),
group = group_var,
line = list(shape = "spline"),
showlegend = FALSE,
hoverinfo = "none")
You can look at the github repo for my submission which includes the code for both ggplot and plotly to produce connected scatterplots.
Using ggplot2:
geom_path() connects the observations in the order in which they appear in the data. geom_line() connects them in order of the variable on the x axis.
Taken from the ggplot manual page: http://docs.ggplot2.org/current/geom_path.html
You may also try out geom_curve and geom_segment if you want more control.
Thanks to #Bishop, I was able to formulate something really close to my ideal orbit chat. I included some chart annotations, for the start and end date and a label for which direction is the optimal solution.
max_date <- final_data_grp[which.max(final_data_grp$week_num), ]
min_date <- final_data_grp[which.min(final_data_grp$week_num), ]
end <- list(
x = max_date$AreaWOH,
y = max_date$SLevel,
text = paste('End', max_date$MondayDate),
xref = "x",
yref = "y"
)
start <- list(
x = min_date$AreaWOH,
y = min_date$SLevel,
text = paste('Start', min_date$MondayDate),
xref = "x",
yref = "y"
)
best_label = list(
x = min(final_data_grp$AreaWOH),
y = max(final_data_grp$SLevel),
text = 'Best Scenario',
showarrow = FALSE,
bordercolor='#c7c7c7',
borderwidth=2,
borderpad=4,
bgcolor='#ff7f0e',
opacity=.7
)
plot_ly(
final_data_grp,
x = AreaWOH,
y = SLevel,
group = MondayDate,
showlegend = FALSE,
marker = list(size = 8,
color = 'black',
opacity = .6)) %>%
add_trace(
x = AreaWOH,
y = SLevel,
line = list(shape = "spline"),
hoverinfo = "none",
showlegend = FALSE) %>%
layout(annotations = list(start, end, best_label))

Resources