Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot geom_point() with colors based on specific, discrete values

Tags:

graph

r

ggplot2

I am trying to plot data points with three different colors for three value ranges. For example:

library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(colour = qsec)) 

The above produces:

enter image description here

Now, I would like to modify this so that qseq values <17 are black, values between 17 and 19 are yellow and values above 19 are red. I've tried various approaches, but none of them seems to work:

  • Taken from here

      ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(fill = qsec)) +    scale_fill_gradient(colours = c("black","yellow","red"),    breaks=c(0,17,19), labels = format(c("0","17","19"))) 

This produces:

enter image description here

So, the colorbar seems correct but the colors are not actually applied.

  • The solutions given in ggplot2 heatmap with colors for ranged values seem promising but I can't get them to work with geom_point().

  • Same goes for various similar posts such as those listed in the sidebar.

I realize I will probably need to use some kind of discrete scale instead of scale_fill_gradientn but my attempts to use scale_color_manual() fail:

ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(color = factor(qsec))) +  scale_color_manual(values=c("black", "yellow","red") Error: Insufficient values in manual scale. 30 needed but only 4 provided. 

I am guessing I will somehow have to use cut() or factor() but I can't seem to figure out how. Any suggestions?

like image 422
terdon Avatar asked Apr 30 '15 11:04

terdon


People also ask

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.

What does %>% do in Ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

What colors does Ggplot recognize?

By default, ggplot graphs use a black color for lines and points and a gray color for shapes like the rectangles in bar graphs.

What is Geom_point Alpha?

Alpha refers to the opacity of a geom. Values of alpha range from 0 to 1, with lower values corresponding to more transparent colors.


1 Answers

You need to cut your values into intervals:

library(ggplot2) ggplot(mtcars, aes(wt, mpg)) +    geom_point(aes(colour = cut(qsec, c(-Inf, 17, 19, Inf))),              size = 5) +   scale_color_manual(name = "qsec",                      values = c("(-Inf,17]" = "black",                                   "(17,19]" = "yellow",                                   "(19, Inf]" = "red"),                      labels = c("<= 17", "17 < qsec <= 19", "> 19")) 

resulting plot

like image 74
Roland Avatar answered Sep 19 '22 13:09

Roland