如何在R中以x轴的区域名称创建组条形图?

问题描述 投票:0回答:1

我是R编程以及Stackoverflow的新手。我正在尝试为y轴上的两个变量和x轴上的区域名称创建组条形图(位置=躲闪)。这是数据:

  TeenTotal SrTotal        Region
1      1882     703 North Eastern
2      2277    1028 North Central
3      1647     627      Southern
4      2299     727       Western

datatableimage

下面的代码有效,但仅适用于一列(此处为SrTotal):

ggplot(Chart2, aes(Region, SrTotal)) + 
 geom_bar(stat="identity", position = "dodge") + 
 scale_fill_brewer(palette = "Set1")

要同时获得SrTotal和TeenTotal这两个列,我正在尝试:

ggplot(Chart2, aes(Region, SrTotal)) + 
 ggplot(Chart2, aes(Region, TeenTotal)) +
 geom_bar(stat="identity", position = "dodge") + 
 scale_fill_brewer(palette = "Set1")

如何在y轴组栏上显示SrTotal和TeenTotal,在x轴上显示区域?另外,我想添加数据标签。如何做到这一点?

r ggplot2 geom-bar
1个回答
0
投票

当您要报告多列数据时,使用tidyr::pivot_longer进行某些重塑通常有助于ggplot。

library(tidyr); library(ggplot2)
Chart2 %>%  
  pivot_longer(TeenTotal:SrTotal, names_to = "Age", values_to = "Total") %>%
  ggplot(aes(Region, Total, fill = Age, label = Total)) +
  geom_col(position = "dodge") +
  geom_text(position = position_dodge(width = 1), vjust = 1.5)

enter image description here

数据

Chart2 <- data.frame(stringsAsFactors=FALSE,
   TeenTotal = c(1882, 2277, 1647, 2299),
     SrTotal = c(703, 1028, 627, 727),
      Region = c("North Eastern", "North Central", "Southern", "Western")
)
© www.soinside.com 2019 - 2024. All rights reserved.