【问题标题】:plot lower and upper limits with two ys用两个 y 绘制下限和上限
【发布时间】:2017-11-26 23:11:36
【问题描述】:

我有一个 df,它是 predict.lm 的输出,附加到另一个 df 两列 labelactual

df <- data.frame(
label = c('A', 'B', 'C', 'D', 'E', 'F', 'G'), 
actual = c(13.9, 13.4, 13.8, 14.3, 14.2, 13.6, 14.1),
fit = c(13.8, 13.9, 14.1, 14.0, 13.9, 14.3, 14.1),
lwr = c(13.6, 13.7, 13.8, 13.8, 13.7, 14.0, 13.9),
upr = c(14.3, 14.2, 14.7, 14.3, 14.1, 14.9, 14.9)
)

我想用lwrupr (所有点的黑线区域)之间的空间来绘制这个图,它是透明的颜色。

我试过这个,它给了我 2 年的情节,但没有间隔。

ggplot(df, aes(x = label, y = fit)) +
  theme_bw() +
  geom_ribbon(aes(ymin = lwr, ymax = upr)) +
  geom_line(color = "blue") +
  geom_point(aes(color = label)) +
  geom_point(aes(x = label, y = actual))

它给了我下面的这个图,但我想要一个像上面那个一样的,空间是灰色的。

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    如果将x定义为连续变量,则可以获得所需的绘图。可以将行索引用作连续的x,然后使用scale_x_continuous 使用所需的标签对其进行标记。

    此外,最好将数据重新整形为长格式并使用key 值来设置颜色美学:

    先提供连续的x并转成长格式:

    library(tidyverse)
    df %>%
      mutate(x = row_number()) %>%
      gather(key, value, 2:5) -> df1
    

    我不确定您是否希望在 lwrupr 之间绘制一个区域或一条线。如果不需要该区域而不是geom_ribbon,您可以使用geom_linerange 绘制由xyminymax 定义的线。您可以向此 geom 提供原始数据框,因为它期望 yminymax 是特定列,而 df1 中不是这种情况。

    ggplot(df1) +
      geom_line(aes(x = x, y = value, color = key)) +
      scale_x_continuous(labels = df$label, breaks = 1:7) +
      geom_linerange(data = df %>%
                       mutate(x = row_number()), aes(x = x, ymin = lwr, ymax = upr)) +
    
      theme_bw() 
    

    要调整整个绘图的外观,您可以使用自定义调色板或 ggpubr 库中的 get_palette 函数(因为您的颜色类似于 jco 配色方案)并添加一些妆容:

      library(ggpubr)  
    
      ggplot(df1) +
        geom_line(aes(x = x, y = value, color = key), size = 1) +
        geom_point(aes(x = x, y = value, color = key), size = 2) +
        scale_x_continuous(labels = df$label, breaks = 1:7) +
        geom_linerange(data = df %>%
                         mutate(x = row_number()), aes(x = x, ymin = lwr, ymax = upr)) +
        scale_color_manual(values = get_palette(palette = "jco", 4), name = "") +
        theme_bw() +
        xlab("label") +
        ylab("Absolute") +
        theme(legend.position = "bottom") 
    

    或者,如果您的意图是描绘lwrupr 的区域:

      ggplot(df1) +
        geom_ribbon(data = df %>%
                         mutate(x = row_number()), aes(x = x, ymin = lwr, ymax = upr), alpha = 0.1) +
        geom_line(aes(x = x, y = value, color = key), size = 1) +
        geom_point(aes(x = x, y = value, color = key), size = 2) +
        scale_x_continuous(labels = df$label, breaks = 1:7) +
        scale_color_manual(values = get_palette(palette = "jco", 4), name = "") +
        theme_bw() +
        xlab("label") +
        ylab("Absolute") +
        theme(legend.position = "bottom") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      相关资源
      最近更新 更多