簡體   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