并排显示数据框中两个变量的条形图
Showing bar plot side by side for two variables in dataframe
我有一个如下所示的数据框:
structure(list(Age_group = c("0-1", "16-40", "2-5", "6-15", "Others"
), Ratio_no_V_tour = c(0.144814506265842, 0.368098268252477,
0.135597426307673, 0.291277451831895, 0.0602123473421132), Ratio_V_tour = c(0.0704375667022412,
0.431100508506498, 0.12103710214075, 0.302278862452131, 0.0751459601983803
)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))
Age_group Ratio_no_V_tour Ratio_V_tour
<chr> <dbl> <dbl>
1 0-1 0.145 0.0704
2 16-40 0.368 0.431
3 2-5 0.136 0.121
4 6-15 0.291 0.302
5 Others 0.0602 0.0751
我想知道如何为列 Ratio_no_V_tour 和 Ratio_V_tour 绘制条形图Age_group。我研究了一些像这样的解决方案 https://dk81.github.io/dkmathstats_site/rvisual-sidebyside-bar.html ;但是,在 link 中显示的示例中,两列具有相同的名称。我可以在这里手动做同样的事情,但我更希望寻找更智能的解决方案来绘制这个
我们可以用base R
barplot
barplot(t(`row.names<-`(as.matrix(df1[-1]), df1$Age_group)),
legend = TRUE, beside = TRUE)
-输出
或者,如果我们想使用 ggplot
,请重塑为 'long' 格式
library(ggplot2)
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(cols = -Age_group) %>%
ggplot(aes(x = Age_group, y = value, fill = name)) +
geom_col(position = 'dodge') +
theme_bw()
-输出
我有一个如下所示的数据框:
structure(list(Age_group = c("0-1", "16-40", "2-5", "6-15", "Others"
), Ratio_no_V_tour = c(0.144814506265842, 0.368098268252477,
0.135597426307673, 0.291277451831895, 0.0602123473421132), Ratio_V_tour = c(0.0704375667022412,
0.431100508506498, 0.12103710214075, 0.302278862452131, 0.0751459601983803
)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))
Age_group Ratio_no_V_tour Ratio_V_tour
<chr> <dbl> <dbl>
1 0-1 0.145 0.0704
2 16-40 0.368 0.431
3 2-5 0.136 0.121
4 6-15 0.291 0.302
5 Others 0.0602 0.0751
我想知道如何为列 Ratio_no_V_tour 和 Ratio_V_tour 绘制条形图Age_group。我研究了一些像这样的解决方案 https://dk81.github.io/dkmathstats_site/rvisual-sidebyside-bar.html ;但是,在 link 中显示的示例中,两列具有相同的名称。我可以在这里手动做同样的事情,但我更希望寻找更智能的解决方案来绘制这个
我们可以用base R
barplot
barplot(t(`row.names<-`(as.matrix(df1[-1]), df1$Age_group)),
legend = TRUE, beside = TRUE)
-输出
或者,如果我们想使用 ggplot
,请重塑为 'long' 格式
library(ggplot2)
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(cols = -Age_group) %>%
ggplot(aes(x = Age_group, y = value, fill = name)) +
geom_col(position = 'dodge') +
theme_bw()
-输出