[英]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.