如果将x定义为连续变量,则可以获得所需的绘图。可以将行索引用作连续的x,然后使用scale_x_continuous 使用所需的标签对其进行标记。
此外,最好将数据重新整形为长格式并使用key 值来设置颜色美学:
先提供连续的x并转成长格式:
library(tidyverse)
df %>%
mutate(x = row_number()) %>%
gather(key, value, 2:5) -> df1
我不确定您是否希望在 lwr 和 upr 之间绘制一个区域或一条线。如果不需要该区域而不是geom_ribbon,您可以使用geom_linerange 绘制由x、ymin 和ymax 定义的线。您可以向此 geom 提供原始数据框,因为它期望 ymin 和 ymax 是特定列,而 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")
或者,如果您的意图是描绘lwr 和upr 的区域:
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")