【问题标题】:ggplot, geom_tile: plot continuous variable using irregular, user-defined, discrete intervalsggplot, geom_tile:使用不规则的、用户定义的、离散的间隔绘制连续变量
【发布时间】:2015-11-28 13:14:58
【问题描述】:

我正在使用 ggplot 和 geom_tile 绘制一个连续变量。默认情况下,它使用连续的颜色条进行绘图。像这样的,

data <- cbind(ID = 1:100, a = runif(100, 0, 1), b = runif(100, 0, 1), c = runif(100, 0, 1))
data <- as.data.frame(data)
data <- melt(data, id.vars = "ID")
colnames(data) <- c("ID", "Parameter", "Value")

p <- ggplot(data, aes(y = ID, x = Parameter)) + geom_tile(aes(fill = Value))
print(p)

这会产生以下情节。

现在,我真正想要的是颜色与离散的、不规则的间隔相对应。例如,[0, 0.2) 为红色,[0.2, 0.5) 为蓝色,[0.5, 1.0] 为紫色。我希望这很简单,但我似乎无法弄清楚如何实现这一点。有什么建议吗?

【问题讨论】:

  • 这个问题有帮助吗? stackoverflow.com/questions/18487369/…
  • 这听起来像是 cutHmisc::cut2 或同等职位的工作。代码可能类似于aes(fill = cut(Value, breaks = c(0, .2, .5, 1), include.lowest = TRUE)),然后在scale_fill_manual 中设置颜色/图例名称。

标签: r ggplot2


【解决方案1】:

感谢@aosmith 的解决方案。这是代码,以防它对某人有用。

p <- ggplot(data, aes(y = ID, x = Parameter)) 
p <- p + geom_tile(aes(fill = cut(Value, breaks = c(0, .2, .5, 1), include.lowest = TRUE)))
p <- p + scale_fill_manual(values = c("red", "blue", "green"),
                           labels = c("[0, 0.2)", "[0.2, 0.5)", "[0.5, 1.0]"),
                           name = "Stuff")
print(p)

这会产生以下情节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-11
    • 2023-03-16
    • 2020-04-04
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    相关资源
    最近更新 更多