Domanda

If I generate a ggplot by:

 x <- rnorm( 10^3, mean=0, sd=1)
 y <- rnorm( 10^3, mean=0, sd=1)
 z=x^2+y^2
 df <- data.frame(x,y,z)
 ggplot(df)+geom_point(aes(x,y,color=z))

By default, this is plotted on a blue scale. How can I combine different colors to make a new scale?

È stato utile?

Soluzione

There is an almost limitless number of ways to set colors in ggplot, so many in fact that it can get confusing. Here are a couple of examples to get you started. See documentation here, here, and here many more options. IMO this site gives an excellent overview of color options in ggplot.

As @rawr points out in the comment, the options all involve some version of scale_color_

scale_color_gradient(...) associates colors with low and high values of the color scale variable and interpolates between them.

ggp <- ggplot(df)+geom_point(aes(x,y,color=z))
ggp + scale_color_gradient(low="red", high="blue")

scale_color_gradientn(...) takes a color palette as argument (e.g., a vector of colors) and interpolates between those. Color palettes can be defined manually or using one of the many tools in R. For example, the RColorBrewer package provides access to the color schemes on www.colorbrewer.org.

library(RColorBrewer)   # for brewer.pal(...)
ggp + scale_color_gradientn(colours=rev(brewer.pal(9,"YlOrRd")))

library(colorRamps)     # for matlab.like(...)
ggp + scale_color_gradientn(colours=matlab.like(10))

scale_color_gradient2(...) produces a divergent color scale, designed for data that has a natural midpoint (your example doesn't...).

ggp +
scale_color_gradient2(low="blue",mid="green",high="red",midpoint=5,limits=c(0,10))

This really just scratches the surface. For example, there is another set of tools in ggplot to deal with discrete color scales.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top