R plotly variable values tick distances to lower graph - r

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)))

Related

Hover is not spot on in R plotly with hovermode 'x unified'

I created a graph with two traces in plotly and I use the hovermode x unified. At some point there is no data for line 2, but there is for line 1. In the hoover I only want to see the information about line 1 then, but it also shows information about the nearest point of line 2. When I zoom in the issue dissapears.
So in short, I want to disable the closest function of the hovermode. How can I do this?
Some sample data + code:
library(plotly)
# dummy data
df_data1 = data.frame(date_input = seq(as.Date('2020/01/01'), as.Date('2022/07/01'), by="week")
, value=1:131)
df_data2 = data.frame(date_input = seq(as.Date('2020/01/01'), as.Date('2022/06/01'), by="week")
, value2=3:129)
plot1 <- plot_ly()
plot1 <- plot1 %>%
add_trace(data = df_data1, x = ~date_input, y = ~value
, type = 'scatter', mode = "lines", yaxis = "y", line = list(color = '#E64B35FF', opacity = 0.8)
, showlegend = FALSE
, hovertemplate = ~paste('# Value1: %{y:.0f}<extra></extra>')) %>%
add_trace(data = df_data2, x = ~date_input, y = ~value2
, type = 'scatter', mode = "lines", yaxis = "y2", line = list(color = '#4DBBD5FF', opacity = 0.8)
, showlegend = FALSE
, hovertemplate = ~paste('# Value2: %{y:.0f}<extra></extra>'))
plot1 %>%
layout(
font = list(size = 10),
xaxis = list(title = list(text = '<b>Date<b>', font = list(size = 12))
, fixedrange = T, showgrid = FALSE, ticks = 'inside', type = 'date'
),
yaxis = list(title = list(text = '<b>Number of value1<b>', font = list(size = 12, color = '#E64B35FF'))
, fixedrange = T
, rangemode = 'tozero', showgrid = FALSE, showline = T, ticks = 'inside'),
yaxis2 = list(overlaying = 'y', side = 'right', fixedrange = T, rangemode = 'tozero', showgrid = FALSE, showline = T, ticks = 'inside'
, title = list(text = '<b>Number of value2<b>', font = list(size = 12, color = '#4DBBD5FF'))),
hovermode = "x unified"
)
As you can see the hovermode shows the value2 information still at 15 june (but it shows the closest data from 1 june.

Plotly: dual y axis graph messing up line graph

I'm trying to make a dual axis plot of rainfall and temperature. I have ordered the months on the bottom, but that causes my line graph to screw up. How do I make sure the added line uses the same x axis?
temprain<-data.frame(month = c(1:12),
Train = c(250,220, 180,97,38,27,31,47,70,140,200,250),
Tair = c(17,16, 15,13,9,6,5,9,12,13,14,16))
tempseq<-seq(0,20,by=0.5)
rainseq<-seq(0,260,by=1)
xlab<-list(type = "category",
categoryorder = "array",
categoryarray = month.name,
showgrid = TRUE,
showline = TRUE,
autorange = TRUE,
showticklabels = TRUE,
ticks = "outside",
tickangle = 0
)
plot_ly(temprain) %>%
add_bars(x = ~MonthName, y = ~Train, type = "bar", name = "Rain") %>%
add_lines(x = ~MonthName, y = ~Tair, yaxis = "y2", name = "Temp") %>%
layout(xaxis = xlab,
yaxis = list(showline = TRUE, side = "left",
title = "Rainfall (mm)Temp", range = tempseq),
yaxis2 = list(showline = TRUE, side = "right",
overlaying = "y", title = "Air Temp (C)", range = rainseq),
showlegend = FALSE,
margin = list(pad = 0, b = 50, l = 50, r = 50))
I tried this as well, and it doesn't work, the temp graph disappears
plot_ly(temprain, x = ~MonthName, y = ~Tair, name = "Temp") %>%
add_bars(x = ~MonthName, y = ~Train, yaxis = "y2", type = "bar", name = "Rain") %>%
layout(xaxis = xlab,
yaxis = list(showline = TRUE, side = "left",
title = "Air Temp (C)", range = tempseq),
yaxis2 = list(showline = TRUE, side = "right",
overlaying = "y",
title = "Rainfall (mm)", range = rainseq),
showlegend = FALSE,
margin = list(pad = 0, b = 50, l = 50, r = 50))
Below is the solution:
Your data:
temprain<-data.frame(month = c(1:12),
Train = c(250,220, 180,97,38,27,31,47,70,140,200,250),
Tair = c(17,16, 15,13,9,6,5,9,12,13,14,16))
Generate a column for month abbreviations from month:
mymonths <- c("Jan","Feb","Mar",
"Apr","May","Jun",
"Jul","Aug","Sep",
"Oct","Nov","Dec")
# match the month numbers against abbreviations:
temprain$MonthAbb = mymonths[ temprain$month ]
# This is the code to archieving a consistent combined graph:
temprain$MonthAbb <- factor(temprain$MonthAbb, levels = c(as.character(temprain$MonthAbb)))
Now plot your data:
fig <- plot_ly(temprain)
# Add the Train trace:
fig <- fig %>% add_trace(x = ~MonthAbb, y = ~Train, name = "Train", type = "bar")
ay <- list(
tickfont = list(color = "red"),
overlaying = "y",
side = "right",
title = "<b>Tair</b>")
# Add the Tair trace:
fig <- fig %>% add_trace(x = ~MonthAbb, y = ~Tair, name = "Tair", yaxis = "y2", mode = "lines+markers", type = "scatter")
fig <- fig %>% layout(yaxis2 = ay,
xaxis = list(title="Month"),
yaxis = list(title="<b>Train</b>"))%>%
layout(xaxis = list(
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff'),
yaxis = list(
zerolinecolor = '#ffff',
zerolinewidth = 2,
gridcolor = 'ffff')
)
fig
Output:

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

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'))

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.

Resources