【问题标题】:R Plotly overlay bar chartR Plotly叠加条形图
【发布时间】:2018-01-06 23:34:58
【问题描述】:

简而言之:使用RPlotly 包,我可以创建一个叠加条形图,其中使用x 轴上的相同位置显示2 个系列吗? google了好久,还是没找到答案。

例如这个可视化:

使用 Plotly 和 R 创建分组(非叠加)堆叠条的代码:

months = 1:12
n1 = runif(12, min = 0, max = 1)
n2 = runif(12, min = 0, max = 1)
dfPlot = data.frame(months, n1, n2)

plot_ly(x = dfPlot [,1],
        y = dfPlot [,2],
        type = 'bar') %>%
add_trace(x = dfPlot[,1],
          y = dfPlot[,3],
          type = 'bar')

如何调整图表以使系列重叠?非常感谢有关如何以类似方式可视化相同信息但具有不同逻辑的建议!

【问题讨论】:

  • 您愿意接受使用ggplotly 的解决方案吗?
  • 感谢@StevenBeaupré 的快速回复。据我所知(虽然从未测试过),输出几乎是相似的,对吧?在那种情况下,想看看如何。

标签: r plotly


【解决方案1】:

使用plotlyggplot2 的开发版本的一种方法

#devtools::install_github('hadley/ggplot2')

library(ggplot2)

p <- ggplot(dfPlot) +
  geom_col(aes(x = month.abb[months], y = n1), 
           fill = "blue", width = 0.2) +
  geom_col(aes(x = month.abb[months], y = n2), 
           alpha = 0.3, fill = "red", width = 0.6) +
  labs(title = "Overlay geom_cols", x = "Months", y = "Measure") +
  theme_minimal()

plotly::ggplotly(p)

【讨论】:

    【解决方案2】:

    添加带有选项barmode = 'overlay'的布局 并更改其中一个数据集的宽度

    months = 1:12
    n1 = runif(12, min = 0, max = 1)
    n2 = runif(12, min = 0, max = 1)
    dfPlot = data.frame(months, n1, n2)
    
    plot_ly(x = dfPlot [,1],
        y = dfPlot [,2],
        type = 'bar', name = "n1") %>%
        add_trace(x = dfPlot[,1],
            y = dfPlot[,3],
            type = 'bar', width = 0.3, name = "n2") %>%
      layout(barmode = 'overlay')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 2012-03-14
      • 2020-03-06
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      相关资源
      最近更新 更多