AK88
AK88

Reputation: 3026

ggplot: gradient fill high and low points

Sample data:

set.seed(123)
dtf <- as.data.frame(rnorm(n = 1000, mean = 0, sd = 0.02))
dtf = as.data.frame(dtf)
dtf = cbind(Obs = rownames(dtf), dtf)
names(dtf)[2] = "random"
head(dtf)

  Obs       random
1   1 -0.011209513
2   2 -0.004603550
3   3  0.031174166
4   4  0.001410168
5   5  0.002585755
6   6  0.034301300

Simple point plot:

gp = ggplot() +
  geom_point(data = dtf, aes(x = Obs, y = random))

gp

I want to fill the high points with darkgreen and low points with darkred. The following is not working:

gp = ggplot() +
  geom_point(data = dtf, aes(x = Obs, y = random)) +
  scale_colour_gradient(low = "darkgreen", mid = "blue", high = "darkred")

gp

Any suggestions, please?

Upvotes: 2

Views: 1055

Answers (2)

Roman Luštrik
Roman Luštrik

Reputation: 70653

You are structuring your ggplot call incorrectly. Why your call is not working is because you have not mapped a color (through aes()) to any variable. Try

ggplot(dtf, aes(x = Obs, y = random, color = random)) +
  geom_point() +
  scale_colour_gradient2(low = "darkgreen", mid = "blue", high = "darkred")

Upvotes: 3

neilfws
neilfws

Reputation: 33782

You need to map colour to a variable using aes and to use mid, you need scale_color_gradient2.

ggplot(dtf, aes(Obs, random)) + 
  geom_point(aes(color = random)) + 
  scale_color_gradient2(low = "darkgreen", mid = "blue", high = "darkred")

Upvotes: 3

Related Questions