Pranav Dubey
Pranav Dubey

Reputation: 1

How to create Group Bar chart in R with Region name on x-axis?

I'm new to R programming as well as on Stackoverflow. I am trying to create a group bar chart (position = dodge) for two variables on y-axis and Region names on x-axis. Here is the data:

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

datatableimage

The below code is working, but for only one column (here, SrTotal):

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

To get both columns, SrTotal & TeenTotal, I am trying this:

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

How can I show SrTotal and TeenTotal on y-axis groupbars and Region on x-axis? Also, I would like to add data labels. How can this be done?

Upvotes: 0

Views: 104

Answers (1)

Jon Spring
Jon Spring

Reputation: 66425

Some reshaping with tidyr::pivot_longer often helps for ggplot when you want to report more than one column of data.

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

Data

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

Upvotes: 1

Related Questions