【问题标题】:How can I create subplots in plotly using R where each subplot is two traces如何使用 R 在 plotly 中创建子图,其中每个子图是两条迹线
【发布时间】:2017-01-04 23:36:03
【问题描述】:

这是一个我卡住的玩具示例

library(plotly)
library(dplyr)

# construct data.frame
df <- tibble(x=c(3,2,3,5,5,5,2),y=c("a","a","a","b","b","b","b"))

# construct data.frame of last y values
  latest <- df %>% 
   group_by(y) %>% 
   slice(n())

# plot for one value of y (NB not sure why value for 3 appears?)
  p <- plot_ly() %>% 
   add_histogram(data=subset(df,y=="b"),x= ~x) %>%   
  add_histogram(data=subset(latest,y=="b"),x= ~x,marker=list(color="red")) %>%
  layout(barmode="overlay",showlegend=FALSE,title= ~y)
  p

如何将这些设置为子图,每个 y 的唯一值一个?在现实世界的示例中,我将有 20 个不同的 y,因此理想情况下会循环或应用代码。此外,最好设置标准的 x 比例,例如 c(1:10) 并具有例如 2 行

TIA

【问题讨论】:

  • add_histogram()??
  • 抱歉,这可能只在开发版本 4 及更高版本中 - 尽管 add-trace 仍然有效。但是,如果您“升级”,您还需要 x= ~x 才能使绘图工作

标签: r for-loop plotly


【解决方案1】:
  1. 建立一个包含每个图的列表
  2. 为直方图手动设置 bin 大小,否则自动选择将为图中的每条迹线选择不同的 bin(使其看起来很奇怪,就像您的示例中每条迹线的条具有不同宽度)
  3. 使用 subplot 将所有内容放在一起
  4. 使用注释列表为各个子图添加标题,如here 所述

像这样:

N = nlevels(factor(df$y))
plot_list = vector("list", N)
lab_list = vector("list", N)

for (i in 1:N) {
  this_y = levels(factor(df$y))[i]
  p <- plot_ly() %>% 
    add_trace(type="histogram", data=subset(df,y==this_y), x=x, marker=list(color="blue"),
              autobinx=F, xbins=list(start=0.5, end=6.5, size=1)) %>%   
    add_trace(type="histogram", data=subset(latest,y==this_y), x = x, marker=list(color="red"), 
              autobinx=F, xbins=list(start=0.5, end=6.5, size=1)) %>%
    layout(barmode="overlay", showlegend=FALSE)
  plot_list[[i]] = p

  titlex = 0.5
  titley = c(1.05, 0.45)[i]
  lab_list[[i]] = list(x=titlex, y=titley, text=this_y, 
                       showarrow=F, xref='paper', yref='paper', font=list(size=18))
}

subplot(plot_list, nrows = 2) %>%
  layout(annotations = lab_list)

【讨论】:

  • 谢谢。我正在接近我现在需要的东西。问题是标记每个单独的情节。使用 title=this_y,只有最后一个值,即 b 显示在顶部(我认为它在您的图像中被截断)。没有为每个子图显示标题如果我将 shareX=TRUE 添加到子图函数,我会得到正确的 this_y 沿 x 轴显示,但仅针对底行。在玩具示例中,它只会显示 b (顶部子图上没有任何内容) 。在我的真实示例中,所有底行的 4 列都有正确的 this_y 显示
  • 谢谢。我得到了大致的要点,但很高兴在几天后等待您的答复
  • 我在标题中添加了注释
  • 谢谢,稍后查看。抱歉没有意识到我必须点击赏金按钮。值得拥有
  • 我尝试了这个解决方案,我得到:add_trace中的错误(。,类型=“直方图”,数据=子集(df,y==this_y),:找不到对象'x'> > subplot(plot_list, nrows = 2) %>% + layout(annotations = lab_list) 名称错误(object)
猜你喜欢
  • 2020-09-25
  • 2020-07-23
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2021-07-21
  • 2021-01-12
  • 2022-01-08
  • 2021-01-23
相关资源
最近更新 更多