我的数据框如下
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))
我需要绘制3个折线图。在这种情况下,我有一个非零列和1列,所有行均为0。在绘制时需要省略该列。
这是绘制图形的代码
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))
}
如何使用R中的plot_ly()动态绘制非零列?
提前感谢!
您可以在循环中添加add_trace并通过if条件指定列选择,如下所示:
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))
如果要为每条线和标记指定特定的颜色,则可以添加颜色列表并对其进行子设置。