如何制作每个 X 轴项目有两个值的垂直条形图

How to make a vertical bar chart with two values per every X axis item

下面是示例数据和到目前为止所做的操作。为了提供上下文,我用代码和标题显示了某些行业。接下来,是三个时间段(第一、第二、第三)。它们分别代表 2020-02-01、2020-04-01 和 2021-07-01,但为了便于处理,我将它们重新命名。目标是制作一个垂直条形图,其中从左到右显示行业,每个行业都有一个条形图表示与每个行业相关的下降和恢复值。所以每个行业 2 个,总共 8 个。因此,对于总非农,将有两个相邻的条形图,而不是彼此堆叠。

当我这样做时,我收到有关“错误:stat_count() 只能具有 x 或 y 美学”的错误。 下面是我用来创建此图表的代码。关于如何解决此错误的任何想法?

library(dplyr)
library(ggplot2)

seriescode <- c(00,11,22,23)
seriestitle <-c("Total Nonfarm","Mining","Utilities","Construction")
first <- c(100,20,32,44)
second <- c(95,17,25,30)
third <- c(98,18,26,33)


bartest <-data.frame(seriescode,seriestitle,first,second,third)


bartest <- bartest %>% mutate(Decline = first - second)
bartest <- bartest %>% mutate(Recovery = third-second)

bartest <- bartest %>% pivot_longer(cols = Decline:Recovery, names_to = "change_type", values_to = "change")


chart4 <- bartest %>%ggplot(aes(x=seriestitle,y=change, fill = change_type))+geom_bar()+labs(x="Industry",y="Net Change")+scale_y_continuous(labels = comma)+ggtitle("Decline and Recovery by Industry")

您需要使用 geom_col 或更改 geom_bar 中的统计数据,原因如下:

?geom_bar

geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead. geom_bar() uses stat_count() by default: it counts the number of cases at each x position. geom_col() uses stat_identity(): it leaves the data as is.

你的结果应该是这样的:

代码

bartest %>%
  mutate(
    Decline = first - second,
    Recovery = third-second
    ) %>% 
  pivot_longer(cols = Decline:Recovery, names_to = "change_type", values_to = "change") %>%
  ggplot(aes(x=seriestitle,y=change, fill = change_type))+
  geom_col(position = "dodge")+
  labs(
    title = "Decline and Recovery by Industry",
    x = "Industry",
    y = "Net Change")

输出

library(tidyverse)

seriescode <- c(00,11,22,23)
seriestitle <-c("Total Nonfarm","Mining","Utilities","Construction")
first <- c(100,20,32,44)
second <- c(95,17,25,30)
third <- c(98,18,26,33)


bartest <-data.frame(seriescode,seriestitle,first,second,third)


bartest <- bartest %>% mutate(Decline = first - second)
bartest <- bartest %>% mutate(Recovery = third-second)
bartest <- bartest %>% pivot_longer(cols = Decline:Recovery, names_to = "change_type", values_to = "change")

bartest %>%
  ggplot(aes(seriestitle, change, fill = change_type)) +
    geom_bar(stat = "identity", position = "dodge")

reprex package (v2.0.1)

于 2021-09-08 创建