Home > OS >  R ggplot2 change geom_bar to a single color
R ggplot2 change geom_bar to a single color

Time:09-07

Based on the code and data below, how can I change the bar colors to a single color #0277BD?

I tried scale_fill_manual(values=c("#0277BD")), but it doesn't work.

Error in `f()`:
! Insufficient values in manual scale. 24 needed but only 1 provided.

I also tried scale_fill_brewer(palette="Blues"), but this doesn't work either.

Warning message:
In RColorBrewer::brewer.pal(n, pal) :
  n too large, allowed maximum for palette Blues is 9
Returning the palette you asked for with that many colors

Data:

df = structure(list(CITYNAME = c("a", "b", "c", 
    "d", "e", "f", "g", 
    "h", "i", "j", "k", 
    "l", "m", "n", "p", "q", 
    "r", "s", "t", "u", 
    "w", "x", "y", "z"), AvgTMin = c(20.28, 
20.38, 20.08, 20.35, 20.38, 20.76, 21, 21.21, 20.45, 20.21, 21.18, 
20.29, 20.61, 20.44, 20.95, 19.75, 20.58, 20.32, 21.05, 20.28, 
20.09, 20.15, 20.73, 20.12)), row.names = c(NA, 
    -24L), class = c("tbl_df", "tbl", "data.frame"))

Code:

# Plot in Fahrenheit

    df %>% mutate(AvgTMin = AvgTMin * (1.8)   32) %>% # Convert from C to F
          ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin, fill = CITYNAME))  
          geom_bar(stat="identity")  
          coord_cartesian(ylim = c(60,70.3))  
          theme(axis.text = element_text(size = 14))  
          geom_text(aes(label=sprintf("%0.2f", AvgTMin)), vjust=-0.2, size = 4)  
          labs(x = NULL, y = "Avg. Min. Temperature \u00B0F")   
          theme(axis.text.x = element_text(angle = 90),  legend.position = 'none')  
          ggtitle("1980-2021 Temperature Trend By City")

CodePudding user response:

You can specify the single color in the geom_bar call:

  geom_bar(stat="identity", fill = "0277BD")  

In your code you can also delete the fill aesthetic in the ggplot call unless you need it for other layers.

CodePudding user response:

Another option if you did want to leave the fill parameter alone, then you could still use scale_fill_manual, but you would need to replicate color for all of the unique values.

library(tidyverse)

df %>%
  mutate(AvgTMin = AvgTMin * (1.8)   32) %>% # Convert from C to F
  ggplot(aes(
    x = reorder(CITYNAME, AvgTMin),
    y = AvgTMin,
    fill = CITYNAME
  ))  
  geom_bar(stat = "identity")  
  coord_cartesian(ylim = c(60, 70.3))  
  theme(axis.text = element_text(size = 14))  
  geom_text(aes(label = sprintf("%0.2f", AvgTMin)), vjust = -0.2, size = 4)  
  labs(x = NULL, y = "Avg. Min. Temperature \u00B0F")  
  theme(axis.text.x = element_text(angle = 90),
        legend.position = 'none')  
  ggtitle("1980-2021 Temperature Trend By City")  
  scale_fill_manual(values = rep_len("#0277BD", length(unique(df$CITYNAME))))

Output

enter image description here

  • Related