R Plotly overlay bar chart

守給你的承諾、 提交于 2021-01-27 18:01:55

问题


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? 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:

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!


回答1:


One way to do it using plotly and the development version of 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)




回答2:


Add a layout with option barmode = 'overlay' and change the width of one of your datasets

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



来源:https://stackoverflow.com/questions/45415155/r-plotly-overlay-bar-chart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!