Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom colors to ggplot

Tags:

r

ggplot2

My main goal is to color elements differently in my plot. To do so, I manually added an extra column with the desired color for each category:

mtcars$color[mtcars$carb = 4] = '#F98866'
mtcars$color[mtcars$carb = 3] = '#68829E'
mtcars$color[mtcars$carb = 2] = '#FF420E'
mtcars$color[mtcars$carb = 1] = '#89DA59'

p <- ggplot(mtcars) + 
    geom_point(aes(wt, mpg,
                   size = disp,
                   color = mtcars$color))# + scale_color_manual(values = mtcars$color)

But when I run the above code, I get this as an output: enter image description here Instead of my specified colors, I get the preset ggplot colors.

But if I uncomment the last line, I partially get what I'm looking for--only one of the colors I wanted.

enter image description here

How can this problem be resolved?

like image 989
Jack Avatar asked Nov 16 '25 22:11

Jack


1 Answers

ggplot(mtcars) + 
    geom_point(aes(wt, mpg, size = disp, color = color)) + 
    scale_color_identity(guide = 'legend')

enter image description here

like image 133
Axeman Avatar answered Nov 18 '25 11:11

Axeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!