代码之家  ›  专栏  ›  技术社区  ›  Tim Wilcox

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

  •  0
  • Tim Wilcox  · 技术社区  · 3 年前

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

    当我这样做时,我得到一个关于“error: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")
    
    2 回复  |  直到 3 年前
        1
  •  2
  •   danlooo    3 年前
    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")
    

    于2021-09-08年由 reprex package (v2.0.1)

        2
  •  2
  •   Vinícius Félix    3 年前

    你需要使用 geom_col geom_bar ,原因如下:

    ?geom_bar
    

    geom_bar()使杆的高度与杆的数量成比例 重量)。如果您希望条形图的高度表示 数据中的值,请改用geom_col()。geom_bar()使用 stat_count()默认情况下:它统计每个x的案例数 位置。geom_col()使用stat_identity():它使数据保持原样。

    结果是:

    代码

    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")
    

    输出

    enter image description here