且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将自定义颜色添加到ggplot

更新时间:2022-10-16 16:18:03

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


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: 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.

How can this problem be resolved?

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