我有一个数据帧,你可以用下面的代码获得它:
x = data.frame(metrics=c("type1", "type1", "type1","type1", "type1", "type1", "orders", "orders", "orders","orders", "orders", "orders", "mean","mean","mean","mean","mean","mean"), hr=c(6,7,8,6,7,8,6,7,8,6,7,8,6,7,8,6,7,8), actual=c(14,20,34,22,24,27,56,12,34,11,15,45,56,78,89,111,123,156), time_pos=c("today", "yesterday", "today", "yesterday", "today", "yesterday"))
基于previous question,我最终得到了以下结果:
plot <- function(df) {
subplotList <- list()
for(metric in unique(df$metrics)){
subplotList[[metric]] <- df[df$metrics == metric,] %>%
plot_ly(
x = ~ hr,
y = ~ actual,
name = ~ paste(metrics, " - ", time_pos),
colors = ~ time_pos,
hoverinfo = "text",
hovertemplate = paste(
"<b>%{text}</b><br>",
"%{xaxis.title.text}: %{x:+.1f}<br>",
"%{yaxis.title.text}: %{y:+.1f}<br>",
"<extra></extra>"
),
type = "scatter",
mode = "lines+markers",
marker = list(
size = 7,
color = "white",
line = list(width = 1.5)
),
width = 700,
height = 620
) %>% layout(autosize = T,legend = list(font = list(size = 8)))
}
subplot(subplotList, nrows = length(subplotList), margin = 0.05)
}
和
plot(x)
给了我这个:
正如您所看到的,它为列"metrics“中的每种值构建了子图,而且,在每个子图上,"time”列中的每种值都有两个散点图(今天,昨天)。但它们是不同的颜色。如何使“今天”和“昨天”值在每个子图中具有相同的颜色?所以在图例中只有两种类型:“今天”和“昨天”,每个小情节的标题是"type1","orders","mean“。
发布于 2020-08-24 08:13:02
这可以像这样实现:
time_pos
on color
,而不是colors
,.i.e color = ~time_pos
。使用colors
,我将调色板设置为默认颜色(否则会收到一堆警告)。today
和yesterday
的两个图例条目。首先在legendgroup
上映射time_pos
,这样所有子图中的轨迹都可以链接起来。其次,使用showlegend
仅显示其中一个图的图例,例如第一个指标。在此post之后,使用
库(绘图) <- function(df) { .pal <- RColorBrewer::brewer.pal(3,"Set2")c(1,3) subplotList <- subplotList() for(metric unique(df$metrics)){ showlegend <- metric == unique(df$metrics)1 subplotList[metric] <- dfdf$metrics == metrics,%>% plot_ly( x=~ hr,y=~ actual,color =~ time_pos,colors = .pal,图例组=文本,显示图例=显示图例,悬停信息=“文本”,悬停模板=粘贴(“%{ ~time_pos }”,"%{xaxis.title.text}:%{x:+.1f}","%{yaxis.title.text}:%{y:+.1f}","“),类型=”散布“,模式= "lines+markers",标记=列表(大小= 7,颜色=“白色”,行=列表(宽度= 1.5) ),宽度= 700,高度= 620 ) %>% add_annotations(文本=~公制,x= 0.5,y= 1,yref =“纸张”,xref =“纸张”,xanchor =“中心”,yanchor =“底部”,showarrow = FALSE,font = list(size = 15) %>% layout(autosize = T,center= list(font = list(size =8)} subplot(subplotList,nrows = length(subplotList),margin = 0.05) } plot(x)
https://stackoverflow.com/questions/63555242
复制相似问题