【问题标题】:ggplot stacked bar graph with 2 columnsggplot 2列堆积条形图
【发布时间】:2016-12-01 16:58:10
【问题描述】:

出于可解释性的原因,我想创建一个我的数据框df 的堆叠条形图,而无需转换数据。我的数据如下所示:

#Code
year <- c(1:5)
burglaries <- c(234,211,201,150,155)
robberies <- c(12, 19,18,23,25)
total <- burglaries + robberies
df <- data.frame(year, burglaries, robberies, total)

#Output
print(df)

  year burglaries robberies total
1    1        234        12   246
2    2        211        19   230
3    3        201        18   219
4    4        150        23   173
5    5        155        25   180

我可以通过如下转换我的数据集来创建我需要的图:

df2 <- rbind(
        data.frame(year, "count" = burglaries, "type"="burglaries"),
        data.frame(year, "count" = robberies, "type"="robberies")
)

ggplot(df2, aes(x=year, y=count, fill=type)) +
    geom_bar(stat="identity")

有没有办法用数据框df 创建相同的图?虽然我可以转换数据,但我担心这会使跟踪程序中发生的事情和捕获错误变得更加困难(我使用的数据集非常大)。

【问题讨论】:

  • 您正在与 ggplot 专门设计用于使用的方式背道而驰。 ggplot 想要你首先转换(融化、收集、整理,无论你想怎么称呼它)你的数据。所以简短的回答是不,不是真的。

标签: r ggplot2


【解决方案1】:

最终需要进行转换,但更优雅的方法是使用 tidyr:

df %>% 
   select(-total) %>% 
   gather(type, count, burglaries:robberies) %>% 
   ggplot(., aes(x=year, y=count, fill=forcats::fct_rev(type))) +
   geom_bar(stat="identity")

【讨论】:

    【解决方案2】:

    我做了一些额外的研究,发现库 plotly 中的 plot_ly() 函数可以让你做到这一点。以下是更多信息的链接:plotly website

    plot_ly(data=df, x = ~year, y = ~burglaries, type = 'bar', name = 'Burglaries') %>%
        add_trace(y = ~robberies, name = 'Robberies') %>%
        layout(yaxis = list(title = 'Count'), barmode = 'stack')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 2016-06-08
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多