library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(size=4)
Suppose you have the above scatterplot
. How can you specify that the points that are >= 25
mpg will be plotted red
, the one between 20 and 25
green
and the 0-20
blue
?
Can this be done with ggplot
specifically?
Sure it can, although this type of work if probably best suited to working with your data frame before
ggplot()
. You could useifelse()
like this:You don't need to call
guides()
to create a title you can pass it to thename = ..
argument inscale_color_manual()
You do this in two steps:
First, you define the groups that should have different colours; either by adding another column to the data frame or inside
aes
. I’ll useaes
here:Secondly, by specifying a manual colour or fill scale:
This specifies which colours to use (
values
) and which labels to assign them to (limits
); these are the names of the grouping generated bycut
.Taken together:
You can improve the legend title by adding the grouping as a separate column to your data, or by providing a
guides
function call: