Coloring ggplot bars based on specific range

I want to color the company bars according to the x-axis range. I know how to solve this error generally but can't figure it out for this specific case. Any help would be appreciated
Error: Aesthetics must be either length 1 or the same as the data (125): colour

static_list <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-06-07/static_list.csv')

install.packages("tidyverse")
library(ggplot2)
df<-head(static_list, -1)
donation<-unlist(df["Amount Contributed Across States"])
company<-unlist(df["Company"])
newdf<-data.frame(donation, company)
minx=min(donation)
maxx=max(donation)
y=(601500-min(donation))/6
while (minx <= 601500)
{
  print(minx)
  minx = minx + y
} 

require(scales)

ggplot(data=newdf, aes(x=donation, y=reorder(company, +donation))) +
  geom_bar(stat="identity") +
  scale_x_continuous(labels = comma)

vals <- minx:maxx
breaks <- c(225.16, 100437.6, 200650.1, 300862.6, 401075.1, 501287.5, 601500)
cols <- c("purple", "blue", "green", "yellow", "orange", "red")[findInterval(vals, vec=breaks)]

1 Like

Hi @shubhangi318 , If i understand well you need something like that

library(tidyverse)

# this for make a new classification according of you request

newdf <- newdf %>% 
  mutate(donation2 = case_when(
    donation <=225.16 ~ "A",
    donation <=100437.6 ~ "B",
    donation <=200650.1 ~ "C",
    donation <=300862.6 ~ "D",
    donation <=401075.1 ~ "E",
    donation <=501287.5 ~ "G",
    donation <=601500 ~ "H"))

# Next the plot 

ggplot(data=newdf, aes(x=donation, y=reorder(company, +donation), fill=donation2)) +
  geom_bar(stat="identity") +
  scale_x_continuous(breaks = c(225.16, 100437.6, 200650.1, 300862.6, 401075.1, 501287.5, 601500)) +
  scale_fill_manual(values=c("purple", "blue", "green", "yellow", "orange", "red", "pink"))+
  theme(legend.position = "none")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.