首页 > 解决方案 > 在 x 轴上带有观察值的分组条形图

问题描述

我有这个data.frame IMPORTS。

description <- c("Agriculture", "Coffee", "Cotton","Potatoes", "Corn")
sept_2020 <- c(825,300,250,150,125)
sept_2019 <- c(720, 280,220,140,80)

IMPORTS <- data.frame(description, sept_2020, sept_2019)

我想要一个这样的酒吧:在此处输入图像描述

但图例将包含变量 sept_2020 和 sept_2019。观察将在 x 轴上。所以,在 x 轴上:“Coffee”的两个条,“Corn”的两个条等等。

有可能这样做吗?如果有人可以提供帮助,我将不胜感激

标签: rggplot2bar-chart

解决方案


试试这个。关键ggplot2是将数据重新整形为长然后绘制它。您拥有宽格式的数据,因此您可以使用重新调整形状pivot_longer(),并且您想要的是可以position_dodge()在数据管道中设置的闪避条。这里的代码:

library(tidyverse)
#Data
description <- c("Agriculture", "Coffee", "Cotton","Potatoes", "Corn")
sept_2020 <- c(825,300,250,150,125)
sept_2019 <- c(720, 280,220,140,80)
IMPORTS <- data.frame(description, sept_2020, sept_2019)
#Plot
IMPORTS %>% pivot_longer(-description) %>%
  ggplot(aes(x=description,y=value,fill=name))+
  geom_bar(stat = 'identity',position = position_dodge(0.9))+
  theme_bw()+
  theme(axis.text = element_text(color='black',face='bold'),
        axis.title = element_text(color='black',face='bold'),
        legend.text = element_text(color='black',face='bold'),
        legend.title = element_text(color='black',face='bold'),
        plot.title = element_text(color='black',face='bold',hjust=0.5))+
  ggtitle('My title')

输出:

在此处输入图像描述


推荐阅读