Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 color gradient per group

Tags:

r

ggplot2

Here is the sample I was able to make it work:

find_hull <- function(df) df[chull(df$Sepal.Length, df$Sepal.Width), ]
hulls <- ddply(iris, "Species", find_hull)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species, 
                         color=Species, size=Petal.Width)) + 
  geom_point() +
  ggtitle("Sepal.Length vs. Sepal.Width - size Petal.Width") +
  scale_shape_manual(values=c(15,16,17)) +
  geom_polygon(data = hulls, alpha = 0.15, size=0.2) +
  scale_size(guide = "none")

What I would like to do now is to specify gradient for each of the groups (i.e., setosa, versicolor, and virginica), based on the Petal.Width. That is, let's say setosa group are read squares, where size of each point depends on the Petal.Width. I would like that this red color varies (from white to red), based on the petal width. If virginica are blue triangles, I would like that color of those triangles also varies with the size (petal width).

Any ideas what would be an easy way to do something like that?

like image 363
Srecko Avatar asked Aug 29 '26 02:08

Srecko


1 Answers

A bit hacky -- to get the "fade to white" effect, I added a white geom_point, and overlaid that with another geom_point where alpha is mapped to Petal.Width. So points with the largest values of Petal.Width will be solid colours, fading to white as Petal.Width decreases.

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species, 
                         color=Species, size=Petal.Width)) + 
  geom_point(colour = "white") +
  geom_point(aes(alpha = Petal.Width, colour = Species)) +
  ggtitle("Sepal.Length vs. Sepal.Width - size Petal.Width") +
  scale_shape_manual(values=c(15,16,17)) +
  geom_polygon(data = hulls, alpha = 0.15, size=0.2) +
  scale_size(guide = "none") +
  scale_alpha_continuous(guide = FALSE) 

Output:

enter image description here

like image 124
Weihuang Wong Avatar answered Aug 30 '26 17:08

Weihuang Wong