【发布时间】:2021-09-14 00:05:57
【问题描述】:
library(ggplot2)
library(scales)
df = data.frame(Type = rep(c('A', 'B'), 250), Index = seq(500), Value = cumsum(rnorm(500)))
colors = hue_pal()(3)
labels = c('Alpha', 'Beta', 'Gamma')
ggplot(df, aes(Index, Value)) +
geom_line(aes(color = Type)) +
geom_segment(x = 200, xend = 300, y = -8, yend = -8, color=colors[1]) + # Label as "Alpha"
geom_segment(x = 400, xend = 500, y = -4, yend = -4, color=colors[1]) + # Label as "Alpha"
geom_segment(x = 0, xend = 100, y = 0, yend = 0, color=colors[2]) + # Label as "Beta"
geom_segment(x = 100, xend = 200, y = 4, yend = 4, color=colors[3]) + # Label as "Gamma"
geom_segment(x = 300, xend = 400, y = 8, yend = 8, color=colors[3]) # Label as "Gamma"
上面的代码产生下面的输出
我想添加第二个图例,标题为“分类”,条目“Alpha”“Beta”和“Gamma”对应于水平线段的三种颜色。 Adding a legend entry for geom_segment 的答案建议使用 scale_fill_manual 但它没有效果。我希望在 R 中有一种干净的方法来做到这一点。
【问题讨论】:
标签: r dataframe ggplot2 time-series data-visualization