[英]Plot multiple variables by year in the same bar plot
我无法弄清楚如何在 ggplot 中创建特定样式的 plot。
我在 tibble 中有如下所示的数据:
indicator 2015 2019
wdi_lfpr 55.6 58.2
wdi_lfprf 34.9 38.2
wdi_lfprm 77.0 78.4
每一年的数值都是百分比。 我想 plot 这些,以便每个指标并排显示,并显示每年(2015、2019)的值。
我不知道如何在 ggplot 中对此进行 go 。 感谢您的任何帮助。
编辑:感谢评论者的建议,我已将我的数据重新调整为这种格式:
indicator year value
wdi_lfpr 2015 55.6
wdi_lfprm 2015 34.9
wdi_lfprf 2015 77.0
wdi_lfpr 2019 58.2
wdi_lfprm 2019 58.2
wdi_lfprf 2019 58.2
一种解决方案是:
library(ggplot2)
library(tidyverse)
library(dplyr)
df = data.frame(year = c(2015, 2019),
wdi_lfpr = c(55.6, 58.2),
wdi_lfprf = c(34.9, 38.2),
wdi_lfprm = c(77.0, 78.4)) %>%
pivot_longer(cols = 2:4, names_to = "indicator", values_to = "percent")
ggplot(df, aes(x = as.factor(year), y = percent, fill = indicator)) +
geom_bar(stat = "identity", position = "dodge")
或者:
ggplot(df, aes(x = as.factor(indicator), y = percent, fill = as.factor(year))) +
geom_bar(stat = "identity", position = "dodge")
正如其他人所提到的,您需要先整理数据,然后才能充分利用ggplot2
:
# Define the dataset
data <- tribble(
~indicator , ~"2015", ~"2019",
"wdi_lfpr" , 55.6 , 58.2,
"wdi_lfprf" , 34.9 , 38.2,
"wdi_lfprm" , 77.0 , 78.4
)
# 'pivot' the data so that every column is a variable
tidy_data <- data %>%
tidyr::pivot_longer(c(`2015`, `2019`), names_to = "year", values_to = "value")
在您的示例 plot 中存在一些问题。
幸运的是,如果您谨慎选择fill
美学, ggplot2
会处理大部分问题:
ggplot(tidy_data, aes(x = indicator, fill = year, y = value)) +
geom_col(position = "dodge")
如果您更喜欢经典的 r-graphics 样式(类似于您的示例)并且您不想使用颜色,您可以使用以下类似的方式来使用theme_classic()
:
ggplot(tidy_data, aes(x = indicator, group = year, y = value)) +
geom_col(position = "dodge", colour = "white") +
theme_classic()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.