简体   繁体   English

R绘制叠加条形图

[英]R Plotly overlay bar chart

Question in short: using R and the Plotly package, can I create an overlay bar chart where 2 series are shown using the same position on the x-axis? 简而言之,问题是:我可以使用RPlotly程序包创建重叠条形图,其中在x轴上的相同位置显示2个系列吗? After quite a bit of Googling, I could not find the answer. 经过大量谷歌搜索后,我找不到答案。

For example this visualisation: 例如,以下可视化:

在此处输入图片说明

Code to create a grouped (not-overlayed) stacked bar, using Plotly and R: 使用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')

在此处输入图片说明

How can I tweak the chart so that the series overlay? 如何调整图表以使序列重叠? Suggestions on how to visualize the same information in a similar way, but with a different logic are also very much appreciated! 我们也非常赞赏有关如何以相似的方式可视化相同信息,但逻辑不同的建议!

One way to do it using plotly and the development version of ggplot2 一种使用plotlyplotly开发版本的ggplot2

#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)

在此处输入图片说明

Add a layout with option barmode = 'overlay' and change the width of one of your datasets 使用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')

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM