ggplot geom_line颜色基于密度函数

时间:2020-03-30 14:07:21

标签: r ggplot2

library(ggplot2)
library(dplyr)
i = rnorm(10000, 5, 1)
tb = tibble(x = i, y = i^2.5)
ggplot(tb, aes(x = x, y = y)) + geom_point(alpha = 0.09, size = 0.2)

enter image description here

由于某些原因,我需要显示一条线而不是单个点:

ggplot(tb, aes(x = x, y = y)) + geom_line()

enter image description here

是否可以使用渐变色来模仿原始数据点的“密度” ,也许可以使用基于x轴(例如density(i)$y)?

1 个答案:

答案 0 :(得分:1)

一种方法是估计密度,然后用approxfun定义近似函数并在x处对其求值。然后只需使用scale_color_gradient

tb %>% mutate(Density = approxfun(density(x),rule=2)(x)) %>%
  ggplot(aes(x = x, y = y,color=Density)) + geom_line() + scale_colour_gradient(low = "white", high = "black")

Plot

相关问题