简体   繁体   中英

Trying to change the colors of the first 3 bars in a bar graph using ggplot and scale_fill_manual

Hello I am trying to plot a bar graph with gglot, the graph has 20 values (20 bars) but I want the first 3 bars to fill in red and the rest in blue. Here is my code but its not giving me my desired output, it is still showing all the bars in blue.

ggplot(data = my_data, aes(x=reorder(cat, -total), y=total))+
  geom_bar(stat = "identity", fill="blue")+
  scale_fill_manual(values=c("red","red","red"))+
  theme(axis.text.x = element_text(angle = 45, hjust=1))+
  scale_y_continuous(labels = comma)

Greatful for all responses, thanks you.

You need to map the x-axis variable to the fill aesthetic, and specify all the fill colors:

library(ggplot2)

my_data <- data.frame(total = round(runif(20) * 10000),
                 cat = LETTERS[1:20])

ggplot(my_data, aes(reorder(cat, -total), y = total)) +
  geom_col(aes(fill = reorder(cat, -total))) +
  scale_fill_manual(values = c(rep("red", 3), rep("blue", 17))) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_continuous(labels = scales::comma) +
  theme(legend.position = "none")

Created on 2022-02-07 by the reprex package (v2.0.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM