ggplot:渐变填充高点和低点

时间:2017-05-25 05:53:08

标签: r ggplot2 gradient

示例数据:

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

简单点图:

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

gp

我想用darkgreen填充高点,用darkred填充低点。以下是行不通的:

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

gp

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您需要使用aes将颜色映射到变量并使用mid,您需要scale_color_gradient2

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

答案 1 :(得分:3)

您正在构建错误的ggplot电话。为什么你的电话不起作用是因为你没有将颜色(通过aes())映射到任何变量。尝试

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