Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ggplot: scale fill manual does not change the colors of the columns

I’m tring to color the columns of my plot, but scale_fill_manual comand doesn’t work… Even if I don’t receive any error message, nothing seems to happen

This is my dataset

# A tibble: 14 Ă— 3
   City                      Wage PPA
   <chr>                    <dbl> <dbl>
 1 Livorno                   17.0 107. 
 2 Siena                     17.6 107. 
 3 Terni                     16.7 107. 
 4 Ancona                    17.3 107. 
 5 Roma                      21.4 107. 
 6 Chieti                    23.7  89.3
 7 Teramo                    23.1  89.3
 8 Brindisi                  24.0  89.3
 9 Agrigento                 23.8  89.3
10 Caltanissetta             24.0  89.3
11 Enna                      24.2  89.3
12 Nuoro                     23.0  89.3
13 Oristano                  23.1  89.3
14 Sassari                   23.7  89.3

This is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dataset%>%
ggplot(aes(x = reorder(City, Wage), y = Wage)) +
  geom_col() +
  coord_flip()+
  scale_fill_manual(values=c(rep("red",5), rep("blue",9)))+
  theme_classic()

I want to color the columns of the first 5 cities in red and the remaining ones in blue. What Am I setting wrong?

>Solution :

We could create a new variable called Color and assign "red" to the first 5 rows and "blue" to the rest.

For this we have to use fill aesthetics in aes as @Rui Barradas already mentioned in the comments. To set the colors to "red" and "blue" we have to further use scale_fill_manual:

library(ggplot2)
library(dplyr)

df %>% 
  mutate(Color = ifelse(row_number() <= 5, "red", "blue")) %>% 
  ggplot(aes(x = reorder(City, Wage), y = Wage, fill = Color)) +
  geom_col() +
  coord_flip() +
  scale_fill_manual(values = c("red", "blue")) +
  theme_classic()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading