R ggplot2 assigning colours to a factor

2019-05-13 05:43发布

问题:

I am trying to plot a scatterdiagram x, y coloured by a factor z (five values) with the colour values assigned by a palette I have tried :

library(ggplot2)

Palette1 <- c('red','green','blue','violet','black')

p <- ggplot(df1, aes(x,y)) 

p + geom_point(aes(colour = factor(z)))
p + scale_colour_manual(values=Palette1 ) 

but I get an error message:

Error: No layers in plot

Thank you for your help.

回答1:

The error comes because you plot:

p + geom_point(aes(colour = factor(z)))

And then try to make a new plot of:

p + scale_colour_manual(values=Palette1)

Which doesn't have any layers in it. Instead, I usually make all my assignments at the time of plotting:

ggpot(df1, aes(x, y, colour=factor(z))) + 
    geom_point() +
    scale_colour_manual(values=Palette1)

Or you can assign your first p + geom_point(...) to p:

p <- p + geom_point(...)

Then proceed as you were.



标签: r ggplot2