【问题标题】:Change the overlaying order of lines in ggplot更改ggplot中行的重叠顺序
【发布时间】:2017-05-04 13:35:33
【问题描述】:

假设我有这个情节:

library(ggplot2)
pl_data <- data.frame(x = rep(c(1, 2), times = 3), y = c(0, 1, 1, 0, .7, .7), col = rep(c("r", "b", "g"), each = 2))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
  geom_line(size = 3)

如何更改绘图顺序,使红线 绘制在其他两个上方?

因此,背景是我的情节非常相似 行,并希望在前景中看到特定的行。

我想这个答案order of stacked bars in ggplot 的内容会起作用。它使颜色列成为因素并改变它们的顺序,但我更愿意改变 这直接在 ggplot 调用的一行中。

我还尝试使用scale_color_discrete(breaks=c("r", "g", "b")) 更改图例顺序), 但这也不影响绘图顺序。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    所以实际上col 的最后一层在顶部。因此,您需要更改因子的顺序并反转颜色,因为红色会自动映射到第一级(使用标准颜色来说明问题):

    pl_data$col <- factor(pl_data$col, c("r", "g", "b"))
    ggplot(pl_data, aes(x = x, y = y, color = col)) +
        geom_line(size = 3) + 
        scale_color_manual(values = c(r = "blue", g = "green", b = "red"))
    
    ## with standard colors of ggplot2, function taken from:
    ## http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
    
    ggplotColours <- function(n = 6, h = c(0, 360) + 15) {
      if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
      hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
    }
    pal <- setNames(ggplotColours(3), c("b", "g", "r"))
    ggplot(pl_data, aes(x = x, y = y, color = col)) +
        geom_line(size = 3) + 
        scale_color_manual(values = pal, breaks = c("b", "g", "r"))
    

    【讨论】:

    • 由于我们示例中的颜色不同,让我有点困惑,但现在效果很好!我想我必须将因素纳入我的 ggplot 例程中。
    • 抱歉,只有红色 r gb 并假设这适合颜色。将相应地编辑我的答案。
    • 再次感谢,现在也可以在我的应用示例中使用。为了澄清我之前第一次混淆的意思:尽管该方法确实有效,但看起来您只需要更改红线和蓝线之间的颜色,因为同一条线在我们的两个图中都位于顶部。 (我只是不应该给我的线条命名 r、b、g,它们与它们的自动颜色不匹配。)
    • @thotal 谢谢,现在完美了。
    【解决方案2】:
    library(ggplot2)
    df <- data.frame(
      x = rep(c(1, 2), times = 3), 
      y = c(0, 1, 1, 0, .7, .7), 
      col = rep(c("r", "b", "g"), each = 2))
    
    ggplot() + 
      geom_line(data = df[3:4,], aes(x = x, y = y), color = 'blue', size = 3) +
      geom_line(data = df[5:6,], aes(x = x, y = y), color = 'green', size = 3) +
      geom_line(data = df[1:2,], aes(x = x, y = y), color = 'red', size = 3)
    

    【讨论】:

    • 在我看来作为备份很好,我有时也会使用它。但它不能以自动 ggplot 方式工作,特别是如果你的数据框是长格式的。
    【解决方案3】:

    您好,当您绘制线条时,它是组 ID - 最高的组 ID 在顶部

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多