[英]Grouped bar plot with observations in the x-axis
我有这个 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)
但是图例将具有变量 sept_2020 和 sept_2019。 观察结果将在 x 轴上。 因此,在 x 轴上:“咖啡”的两个条形,“玉米”的两个条形,依此类推。
有可能这样做吗? 如果有人可以提供帮助,我很感激
尝试这个。 ggplot2
的关键是将数据重塑为 long 然后将其绘制。 您拥有宽格式的数据,因此您可以使用pivot_longer()
重塑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')
输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.