简体   繁体   English

在 x 轴上有观测值的分组条形图

[英]Grouped bar plot with observations in the x-axis

I have this data.frame IMPORTS.我有这个 data.frame 导入。

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)

I would like a bar like that:我想要一个这样的酒吧: 在此处输入图片说明

But the legend would have the variables sept_2020 and sept_2019.但是图例将具有变量 sept_2020 和 sept_2019。 The observations would be in the x-Axis.观察结果将在 x 轴上。 So, in x-axis: two bars for "Coffee", two bars for "Corn" and so on.因此,在 x 轴上:“咖啡”的两个条形,“玉米”的两个条形,依此类推。

It's possible to do that?有可能这样做吗? I appreciate if someone can help如果有人可以提供帮助,我很感激

Try this.尝试这个。 The key in ggplot2 is to reshape data to long and then plot it. ggplot2的关键是将数据重塑为 long 然后将其绘制。 You have data in wide format so you can reshape using pivot_longer() and what you want is dodged bars that can be set with position_dodge() in the data pipleine.您拥有宽格式的数据,因此您可以使用pivot_longer()重塑pivot_longer() ,您想要的是可以在数据管道中使用position_dodge()设置的躲避条。 Here the code:这里的代码:

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

Output:输出:

在此处输入图片说明

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

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