【问题标题】:Applying a gradient fill on a density plot in ggplot2在 ggplot2 的密度图上应用渐变填充
【发布时间】:2017-08-14 15:06:43
【问题描述】:

是否可以在 ggplot2 的密度图中添加渐变填充,使图表中的颜色沿 x 轴变化?在下面的示例中,fill 参数似乎被忽略了。

library(ggplot2)
ggplot(data.frame(x = rnorm(100)), aes(x = x, fill = x)) + geom_density()

【问题讨论】:

  • @Masoud 这回答了一个不同的问题,因为它离散了规模。我不想那样做。
  • 只是一个建议。这就是为什么我没有将其标记为欺骗。

标签: r ggplot2


【解决方案1】:

总是可以选择手动计算密度:

set.seed(123)
x <- rnorm(100)
y <- density(x, n = 2^12)
ggplot(data.frame(x = y$x, y = y$y), aes(x, y)) + geom_line() + 
  geom_segment(aes(xend = x, yend = 0, colour = x)) + 
  scale_color_gradient(low = 'green', high = 'red')

【讨论】:

  • “手工”是一个额外的 loc 的费力路由,哈哈
【解决方案2】:

ggridges 库有你的答案。

这是一些可重复的数据:

library(ggplot2)
library(ggridges)

input   = runif(1000, 0, 1)
output  = exp(input) + cos(input)^runif(1000,0,1)

现在我们需要创建一个虚拟因子,将其全部包装在一个数据框中,然后将虚拟变量标记为因子:

name    = rep("Name", length(output))
data    = data.frame(input, output, name)
data$name = as.factor(data$name)

从这里我们可以构建密度图:

ggplot(data, aes(x=output, y=name, fill=..x..))+
    geom_density_ridges_gradient()+
    scale_fill_gradient(low="orange", high="navy")

根据 x 轴值生成梯度填充的密度图。当然,从这一点开始,您可以使用 ggplot2 库在图表上添加/减去您想要的任何内容。

Gradient Filled Density Plot - Example

【讨论】:

    猜你喜欢
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多