MLEN
MLEN

Reputation: 2561

ggplot2: Color contionous variable depending on factor also

ggplot(data = filter(My.Map, Year == 1435 & Some.Factor == 1), aes(x=long, y=lat, group = Group.Var, fill=as.numeric(Ageincrease))) + 
  geom_polygon() +
  scale_fill_continuous(name="Age increase") +
  geom_path(color = "white") +
  coord_equal() +
  coord_quickmap()

Unfortunately no example data. My data consist of one variable - Ageincrease which I would like to fill as contionous on the map. If postive, blue, and if negative red. But also gradient, with 2 color bars on the side. Some.Factor is a variable I created to indicate if Ageincrease is negative/postive.

Upvotes: 1

Views: 74

Answers (1)

Jonathan Carroll
Jonathan Carroll

Reputation: 3947

scale_colour_gradient2() produces a gradient scale for a continuous variable between red and blue, by default. Set the midpoint argument to something meaningful to your data (default is 0).

library(ggplot2)

ggplot(mtcars, aes(x=disp, y=mpg, col=hp)) + 
  geom_point(size = 5) +
  scale_color_gradient2(midpoint = mean(mtcars$hp)) +
  theme_bw()

Equivalently, scale_fill_gradient2().

Upvotes: 1

Related Questions