Home > Software engineering >  Bar plot shows color by group in ggplot
Bar plot shows color by group in ggplot

Time:03-13

I've dataframe as follows:

df2 <- structure(list(City = c("Naypyitaw", "Yangon", "Yangon", "Naypyitaw", 
"Mandalay", "Mandalay", "Mandalay", "Naypyitaw", "Yangon"), month = structure(c(1L, 
1L, 3L, 3L, 1L, 3L, 2L, 2L, 2L), .Label = c("Jan", "Feb", "Mar", 
"Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
), class = "factor"), gross.income = c(1925.461, 1841.9585, 1793.2915, 
1771.383, 1770.2885, 1647.4925, 1639.251, 1568.3325, 1421.9105
)), row.names = c(NA, -9L), groups = structure(list(City = c("Mandalay", 
"Naypyitaw", "Yangon"), .rows = structure(list(5:7, c(1L, 4L, 
8L), c(2L, 3L, 9L)), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

I'm trying to plot a bar plot for months again gross.income. Although I'm getting the plot as follows: enter image description here

I do not want the colors by the group. I want something like this: enter image description here

My code:

df2$month <- factor(df2$month, levels = month.abb)

plot3 <- ggplot(df2, aes(x = month, y = gross.income, fill = gross.income))  
  geom_bar(stat = "identity")  
  scale_x_discrete(limits = month.abb[1:3]) 

CodePudding user response:

If you only want one colour per bar, you need to have only one entry per month. Therefore you need to summarise your data before ggplot().

library(tidyverse)

df2 %>% 
  group_by(month) %>% 
  summarize(gross.income = sum(gross.income)) %>% 
  ggplot(aes(month, gross.income, fill = gross.income))  
  geom_bar(stat = "identity")

Created on 2022-03-12 by the reprex package (v2.0.1)

  • Related