Chart values have been multiplied by 100 when tickformat=% was added - r

I have the stacked bar below in which everything works fine except from the values in the axes and the hovertext which seem to have been multiplied by 100. I tried to to trick it by dividing my initial values with 100 but then I was taking rounded values back (20 instead of 19.8). I think that happened after I added tickformat=%
# 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("#458d35", "#63bb47", "#e6e7e8"),
hovertemplate = paste('<b>%{y}</b>',
'<br>%{text}: %{x} ',
'<extra></extra>')) %>%
layout(font = list(color = '#a2a2a2'),barmode = "stack",
bargap = 0.7,
yaxis = list(fixedrange = TRUE,autorange="reversed",
title = "",
showticklabels = FALSE,
showgrid = FALSE,
showline = FALSE,
zeroline = FALSE),
xaxis = list(fixedrange = TRUE,title = "",
tickformat = "%",
zeroline = FALSE,
showgrid = FALSE),
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%)",
showarrow = FALSE,
x = 70,
y = 1.05,
yref = "paper"),
legend = list(orientation = 'h'))

Use ticksuffix = '%'.
library(plotly)
plot_ly(data.long) %>%
add_bars(y = ~Category,
x = ~percent,
color = ~vac,
text = ~vac,
colors = c("#458d35", "#63bb47", "#e6e7e8"),
hovertemplate = paste('<b>%{y}</b>',
'<br>%{text}: %{x} ',
'<extra></extra>')) %>%
layout(font = list(color = '#a2a2a2'),barmode = "stack",
bargap = 0.7,
yaxis = list(fixedrange = TRUE,autorange="reversed",
title = "",
showticklabels = FALSE,
showgrid = FALSE,
showline = FALSE,
zeroline = FALSE),
xaxis = list(fixedrange = TRUE,title = "",ticksuffix = '%',
zeroline = FALSE,
showgrid = FALSE),
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%)",
showarrow = FALSE,
x = 70,
y = 1.05,
yref = "paper"),
legend = list(orientation = 'h'))

Related

Decrease the distance between bars in plotly while keeping them slim with bargap

I have used bargap to decrease the width of bars in plotly but I want to bring themcloser whild keeping this width and not make them thicker.
library(tidyr)
library(stringr)
library(forcats)
library(plotly)
# 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)))
library(plotly)
plot_ly(data.long) %>%
add_bars(y = ~Category,
x = ~percent,
color = ~vac,
text = ~vac,
colors = c("#458d35", "#63bb47", "#e6e7e8"),
hovertemplate = paste('<b>%{y}</b>',
'<br>%{text}: %{x} ',
'<extra></extra>')) %>%
layout(font = list(color = '#a2a2a2'),barmode = "stack",
bargap = 0.7,
yaxis = list(fixedrange = TRUE,autorange="reversed",
title = "",
showticklabels = FALSE,
showgrid = FALSE,
showline = FALSE,
zeroline = FALSE),
xaxis = list(fixedrange = TRUE,title = "",ticksuffix = '%',
zeroline = FALSE,
showgrid = FALSE),
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%)",
showarrow = FALSE,
x = 70,
y = 1.05,
yref = "paper"),
legend = list(orientation = 'h'))

R plotly variable values tick distances to lower graph

I hope I explain it correctly but I have 2 graphs in 1 plot (so 2 y-axes). I would like to have y-axis2 lowered, so thats it not plotted in the whole plot (so I guess have variable values for the same tick distances). How is this possible?
df <- data.frame(x = 1:50,
y1 = c(20:5,6:10,9:3,4:20, 19:15),
y2 = c(100:115,200:204,50:44,4:20, 66:62))
plot_ly(df) %>%
add_lines(type = 'scatter', mode = "lines",
name = "test",
x = ~x, y = ~y1,
line = list(color = '#999999'),
hoverinfo = "text",
text = ~paste(round(y1, 1), x)) %>%
add_lines(type = 'scatter', mode = "lines",
name = "test", yaxis = 'y2',
x = ~x, y = ~y2,
line = list(color = '#CC79A7'),
hoverinfo = "text",
text = ~paste(round(y2, 1), x)) %>%
#layout
layout(title = "test",
xaxis = list(titel = "Date",
rangeslider = list(thickness = 0.05)),
yaxis = list(side = 'left', title = 'test',
showgrid = F, zeroline = F, type = "log",
showline = T),
yaxis2 = list(side = 'right', overlaying = "y",
title = 'test',
showgrid = F, zeroline = F,
showline = T))
You can expand the axis with range and therefore lower the 200 position. And if you like to hide the values over 200, you may use ticktext and tickvals for showing just the values between 0 and 200.
plot_ly(df) %>%
add_lines(type = 'scatter', mode = "lines",
name = "test",
x = ~x, y = ~y1,
line = list(color = '#999999'),
hoverinfo = "text",
text = ~paste(round(y1, 1), x)) %>%
add_lines(type = 'scatter', mode = "lines",
name = "test", yaxis = 'y2',
x = ~x, y = ~y2,
line = list(color = '#CC79A7'),
hoverinfo = "text",
text = ~paste(round(y2, 1), x)) %>%
#layout
layout(title = "test",
xaxis = list(titel = "Date",
rangeslider = list(thickness = 0.05)),
yaxis = list(side = 'left', title = 'test',
showgrid = F, zeroline = F, type = "log",
showline = T),
yaxis2 = list(side = 'right', overlaying = "y",
title = 'test',
showgrid = F, zeroline = F,
showline = T,
# added code
range = list(0, 700),
tickvals = seq(0, 200, 50),
ticktext = seq(0, 200, 50)))

R Plotly add image watermark

I would like to have an image/watermark added to a double y-axis plot, somehow my code doesnt work..... How is this possible? It doesnt error but the image is not added
df <- data.frame(x = 1:50,
y1 = c(20:5,6:10,9:3,4:20, 19:15),
y2 = c(100:115,200:204,50:44,4:20, 66:62))
And my code
plot_ly(df) %>%
add_lines(type = 'scatter', mode = "lines",
name = "test",
x = ~x, y = ~y1,
line = list(color = '#999999'),
hoverinfo = "text",
text = ~paste(round(y1, 1), x)) %>%
add_lines(type = 'scatter', mode = "lines",
name = "test", yaxis = 'y2',
x = ~x, y = ~y2,
line = list(color = '#CC79A7'),
hoverinfo = "text",
text = ~paste(round(y2, 1), x)) %>%
#layout
layout(title = "test",
xaxis = list(titel = "Date",
rangeslider = list(thickness = 0.05)),
yaxis = list(side = 'left', title = 'test',
showgrid = F, zeroline = F, type = "log",
showline = T),
images = list(source = "https://rstudio.com/wp-content/uploads/2018/10/RStudio-Logo.png",
xref = "paper",
yref = "paper",
xanchor = "left",
yanchor = "bottom",
x= 4,
y=4,
sizex = 5,
sizey = 5,
opacity = 0.8),
yaxis2 = list(side = 'right', overlaying = "y",
title = 'test',
showgrid = F, zeroline = F,
showline = T))
The problem is that you have no access to the Rstduio-logo.png.
Create a www folder
Put a .png in this www folder let's say I call it test.png
Then simply:
layout(images = list(source = "test.png"))

Plot the line graph only for the non-zero columns using plot_ly() in R

I'm having a dataframe as follows
avgHours <- data.frame("QuarterYear" = c('2019 Q4','2020 Q1','2020 Q2'), average = c(44.5,44.5,42.0), leave = c(24.0,9.3,0.0), freeTime = c(0,0,0))
I need to plot 3 line graphs. In this case, I'm having a non-zero columns and 1 column with all the rows as 0. I need to omit that column while plotting.
This is the code for plotting the graph
plot_ly(avgHours) %>%
add_trace(x = avgHours$QuarterYear,
y = avgHours$average,
type = 'scatter',
mode = 'lines+markers+text',
hovertext = paste('Quarter: ', avgHours$QuarterYear,
'<br>Average hours per week: ', avgHours$average),
line = list(color = 'rgb(242,142,43)',
width = 3),
marker = list(color = 'rgb(242,142,43)',
size = 8),
hoverinfo = "text",
text = avgHours$average,
textposition = "top center",
name = "Average Hours")%>%
add_trace(x = avgHours$QuarterYear,
y = avgHours$leave,
type = 'scatter',
mode = 'lines+markers+text',
hovertext = paste('Quarter: ', avgHours$QuarterYear,
'<br>Average OOO hours per week: ', avgHours$leave),
line = list(color = 'rgb(205, 12, 24)',
width = 3),
marker = list(color = 'rgb(205, 12, 24)',
size = 8),
hoverinfo = "text",
text = avgHours$leave,
textposition = "top center",
name = "Leave Average Hours")%>%
add_trace(x = avgHours$QuarterYear,
y = avgHours$freeTime,
type = 'scatter',
mode = 'lines+markers+text',
hovertext = paste('Quarter: ', avgHours$QuarterYear,
'<br>Average Free Time per week: ', avgHours$freeTime),
line = list(color = '#003049',
width = 3),
marker = list(color = '#003049',
size = 8),
hoverinfo = "text",
text = avgHours$freeTime,
textposition = "top center",
name = "Free Time Average Hours")%>%
layout(
yaxis = list(
range = c(0,70),
title = "Average Hours Per Week"
)
) %>%
layout(hoverlabel = list(bgcolor= 'white'), showlegend = TRUE) %>%
layout(yaxis = list(showgrid = FALSE, zeroline = FALSE, showline = FALSE)) %>%
layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showline = FALSE)) %>%
layout(legend = list(orientation = "h",
xanchor = "center",
x = 0.5,
y = -0.13))
}
How can I plot the non-zero columns dynamically using plot_ly() in R?
Thanks in advance!!
You can have the add_trace in loop and specify the column selection by if condition as below:
p <- plot_ly(data = avgHours)
for(i in colnames(avgHours[-1])){
if(sum(avgHours[[i]])>0){
p <- p %>%
add_trace(x = avgHours[[1]],
y = avgHours[[i]],
type = 'scatter',
mode = 'lines+markers+text',
hovertext = paste('Quarter: ', avgHours[[1]],
'<br>Average hours per week: ', avgHours[[i]]),
line = list(width = 3),
marker = list(size = 8),
hoverinfo = "text",
text = avgHours[[i]],
textposition = "top center",
name = i)
}
}
p <- p %>%
layout(yaxis = list(
range = c(0,70),
title = "Average Hours Per Week")) %>%
layout(hoverlabel = list(bgcolor= 'white'), showlegend = TRUE) %>%
layout(yaxis = list(showgrid = FALSE, zeroline = FALSE, showline = FALSE)) %>%
layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showline = FALSE)) %>%
layout(legend = list(orientation = "h", xanchor = "center", x = 0.5, y = -0.13))
If you want to have specific colours for each line and markers, you can add the list of colours and sub-setting it.

Two X-axis in Plotly for R

https://community.plot.ly/t/how-to-plot-multiple-x-axis-in-plotly-in-r/3014/3?u=him4u324
I have posted my question on Plotly community as well
I am trying to display two x-axis with common Y-axis on plotly for R. I was able to do so as well but starting point for each x-axis is separated from each other Whereas I wish them to be represented a common y-axis.
f1 <- list(
family = "Arial, sans-serif",
size = 18,
color = "grey"
)
f2 <- list(
family = "Old Standard TT, serif",
size = 14,
color = "#4477AA"
)
# bottom x-axis
ax <- list(
title = "Number of PBIs",
titlefont = f1,
anchor = "y",
side = "bottom",
showticklabels = TRUE,
tickangle = 0,
tickfont = f2
)
# top x-axis
ax2 <- list(
title = " ",
overlaying = "x",
anchor = "y",
side = "top",
titlefont = f1,
showticklabels = TRUE,
tickangle = 0,
tickfont = f2
)
# common y-axis
ay <- list(
title = "Process & Sub-Process Areas",
titlefont = f1,
showticklabels = TRUE,
tickangle = 0,
tickfont = f2
)
plot_ly(data = scrum %>%
group_by(Master.Project) %>%
summarise(Total_PBIs_Planned=sum(PBIs.Planned.in.Sprint, na.rm = TRUE),
Total_PBIs_Delivered = sum(Actual.PBI.Delivery,na.rm = TRUE)) %>% inner_join(scrum %>% count(Master.Project)), # creating the desired data frame
color = I("#149EF7")) %>%
# for bottom x-axis
add_segments(x = ~Total_PBIs_Planned, xend = ~Total_PBIs_Delivered,
y = ~Master.Project, yend = ~Master.Project, showlegend = FALSE) %>%
add_trace(x = ~Total_PBIs_Planned, y = ~Master.Project,
name = "Total_PBIs_Planned", type = 'scatter',mode = "markers",
marker = list(color = "#149EF7", size = 15,
line = list(color = '#FFFFFF', width = 1))) %>%
add_trace(x = ~Total_PBIs_Delivered, y = ~Master.Project,
name = "Total_PBIs_Delivered",type = 'scatter',mode = "markers",
marker = list(symbol ="circle-dot",color = "#F71430", size = 10,
line = list(color = '#FFFFFF', width = 1))) %>%
# for top x-axis
add_trace(x = ~n, y = ~Master.Project, xaxis = "x2",
name = "No._of_Sub_projects",type = 'bar',
marker = list(color = "#149EF7"),
opacity = 0.1,
hoverinfo = 'text',
text = ~paste(
Master.Project,
'<br> Total Sub Projects: ',n,
'<br> PBIs Planned: ',Total_PBIs_Planned,
'<br> PBIs Delivered: ',Total_PBIs_Delivered
)
) %>%
plotly::layout(
title = "Product Backlog Items - Planned Vs Delivered", titlefont = f1,
xaxis = ax,
yaxis = ay,
xaxis2 = ax2,
margin = list(l = 250)
)
You want to use rangemode = "tozero" in your axis layout.
ax <- list(
title = "Number of PBIs",
titlefont = f1,
anchor = "y",
side = "bottom",
showticklabels = TRUE,
tickangle = 0,
tickfont = f2,
rangemode = 'tozero')
Or you can specify your specific ranges using
range = c(0, 5)
See Plotly help here: https://plot.ly/r/axes/#rangemode

Resources