首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Сustomize R plots在子图中绘制颜色

Сustomize R plots在子图中绘制颜色
EN

Stack Overflow用户
提问于 2020-08-24 05:34:06
回答 1查看 596关注 0票数 1

我有一个数据帧,你可以用下面的代码获得它:

代码语言:javascript
运行
AI代码解释
复制
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,我最终得到了以下结果:

代码语言:javascript
运行
AI代码解释
复制
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)
}

代码语言:javascript
运行
AI代码解释
复制
plot(x)

给了我这个:

正如您所看到的,它为列"metrics“中的每种值构建了子图,而且,在每个子图上,"time”列中的每种值都有两个散点图(今天,昨天)。但它们是不同的颜色。如何使“今天”和“昨天”值在每个子图中具有相同的颜色?所以在图例中只有两种类型:“今天”和“昨天”,每个小情节的标题是"type1","orders","mean“。

EN

回答 1

Stack Overflow用户

发布于 2020-08-24 08:13:02

这可以像这样实现:

  1. 可在所有绘图中获得相同的颜色地图time_pos on color,而不是colors,.i.e color = ~time_pos。使用colors,我将调色板设置为默认颜色(否则会收到一堆警告)。

  1. 棘手的部分是只获取todayyesterday的两个图例条目。首先在legendgroup上映射time_pos,这样所有子图中的轨迹都可以链接起来。其次,使用showlegend仅显示其中一个图的图例,例如第一个指标。

在此post之后,使用

  1. 将标题添加到我使用的子图中

库(绘图) <- 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)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63555242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档