r - ggplot 堆叠条形图 2 列

标签 r ggplot2

出于可解释性原因,我想创建数据框 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")

enter image description here

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

最佳答案

我做了一些额外的研究,发现 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')

enter image description here

关于r - ggplot 堆叠条形图 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40916252/

相关文章:

r - 使用分面在 geom_bar 中的列上方添加百分比

r - ggplot 中每组的平均值

使用 R 中的 tbl_regression 函数在一列中具有 95%CI 的回归系数?

r - 如何根据特定字符包装字符向量?

r - 如何查找 R 矩阵中包含大于或等于给定数字的值的列数?

R:使用多个条件为 data.table 赋值的有效方法

r - 最小化重新分配个人的成本

r - 忽略 ggplot2 箱线图中的异常值

r - ggplot2 faceting - 标签重新排序时绘图不重新排序

调整 strip.background 的大小以匹配 ggplot facet_wrap 中的 strip.text