我有如下所示的数据:
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绘制一个条形图,为每个Age_group绘制一个Ratio_V_tour。我研究了一些解决方案,比如这个https://dk81.github.io/dkmathstats_site/rvisual-sidebyside-bar.html;但是,在链接中显示的示例中,两列具有相同的名称。我可以在这里手动地做同样的事情,但是我更多的是寻找更聪明的解决方案来绘制这个图。
发布于 2021-08-27 02:12:46
我们可以使用base R barplot
barplot(t(`row.names<-`(as.matrix(df1[-1]), df1$Age_group)),
legend = TRUE, beside = TRUE)-output

或者,如果我们想要使用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()-output

https://stackoverflow.com/questions/68947230
复制相似问题