繁体   English   中英

Plot 多个变量按年份在同一栏中 plot

[英]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 带颜色

在您的示例 plot 中存在一些问题。

  • 轴没有正确标记
  • 没有什么可以区分每组中的酒吧
  • x 轴文本与数据中的任何列都不匹配

幸运的是,如果您谨慎选择fill美学, ggplot2会处理大部分问题:

ggplot(tidy_data, aes(x = indicator, fill = year, y = value)) +
  geom_col(position = "dodge")

默认 ggplot2 样式的绘图

经典款 Plot

如果您更喜欢经典的 r-graphics 样式(类似于您的示例)并且您不想使用颜色,您可以使用以下类似的方式来使用theme_classic()

ggplot(tidy_data, aes(x = indicator, group = year, y = value)) +
  geom_col(position = "dodge", colour = "white") +
  theme_classic()

没有色彩的经典风格情节

感谢大家的帮助。 在重塑数据后,我能够通过建议的输入达到这个解决方案:

ggplot(long_df, aes(x = as.factor(indicator), y = value, fill = as.factor(year))) +
        geom_bar(stat = "identity", position = "dodge")

这让我产生了这个数字,这是我的目标:

图表完成

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM