R中的堆积条ggplot2
Stacked bar ggplot2 in R
我有一个 table 这样的:
dput
的数据
dput(data)
structure(list(status = c("Recovered", "Dead", "On-Treatment"
), northern_countries = c(24130778L, 955048L, 15634207L), Southern_countries = c(9157967L,
308243L, 726474L)), class = "data.frame", row.names = c(NA, -3L
))
status northern_countries Southern_countries
1 Recovered 24130778 9157967
2 Dead 955048 308243
3 On-Treatment 15634207 726474
我想创建一个堆叠条形图,显示死亡、恢复和治疗中的百分比,其中 2 个条是 northern_countries 和 southern_countries。
我一直在四处寻找,但找不到答案:(另外,我刚刚开始使用 R,所以如果您能详细说明一下,我将不胜感激。
非常感谢xoxo
使用 ggplot2:
假设 df
是您的数据框的名称,首先您需要使用 tidyr
包中的 pivot_longer()
将其转换为长格式:
df <- tidyr::pivot_longer(df, cols=-1)
Obs:-1
不会将第一行转换为长行。然后它应该看起来像这样(抱歉质量不好):
所以我们想要 x 轴上的 name
列(其中每个值一个柱状图),y 轴上的 value
柱状图,每个柱状图应按颜色划分 status
, 所以我们把它传递给 fill
:
library(ggplot2)
ggplot(df, aes(x=name, y=value, fill=status) + geom_col()
我有一个 table 这样的:
dput
的数据
dput(data)
structure(list(status = c("Recovered", "Dead", "On-Treatment"
), northern_countries = c(24130778L, 955048L, 15634207L), Southern_countries = c(9157967L,
308243L, 726474L)), class = "data.frame", row.names = c(NA, -3L
))
status northern_countries Southern_countries
1 Recovered 24130778 9157967
2 Dead 955048 308243
3 On-Treatment 15634207 726474
我想创建一个堆叠条形图,显示死亡、恢复和治疗中的百分比,其中 2 个条是 northern_countries 和 southern_countries。
我一直在四处寻找,但找不到答案:(另外,我刚刚开始使用 R,所以如果您能详细说明一下,我将不胜感激。
非常感谢xoxo
使用 ggplot2:
假设 df
是您的数据框的名称,首先您需要使用 tidyr
包中的 pivot_longer()
将其转换为长格式:
df <- tidyr::pivot_longer(df, cols=-1)
Obs:-1
不会将第一行转换为长行。然后它应该看起来像这样(抱歉质量不好):
所以我们想要 x 轴上的 name
列(其中每个值一个柱状图),y 轴上的 value
柱状图,每个柱状图应按颜色划分 status
, 所以我们把它传递给 fill
:
library(ggplot2)
ggplot(df, aes(x=name, y=value, fill=status) + geom_col()