r - 在 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”的两个条等等。
有可能这样做吗?如果有人可以提供帮助,我将不胜感激
解决方案
试试这个。关键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')
输出:
推荐阅读
- java - 在 chrome 浏览器中进行视觉验证时,为什么 Selenium 没有打开点击的链接?
- ssl - ldapsearch 无法建立安全连接
- rest - Adobe AIR 中的持久 HTTPS 连接
- excel - 将第一列中的文本拆分为几列
- java - 在 Spring Boot 中将 jsessonid cookie 设置为 SameSite=Strict 属性?
- fiware - 查询按关系过滤的实体时如何避免注册结果
- python - python - 计算巨大图节点的加权介数中心性
- git - 漂亮格式占位符之间的 git 空间
- c - 如何准确读取管道中的消息长度?
- angular - 如何使用 Firebase 和 Ionic 和 Cordova 记录事件