【问题标题】:Variable line limits with ggplot()ggplot() 的可变行限制
【发布时间】:2019-05-31 07:17:31
【问题描述】:

我正在一对轴上绘制多个时间序列。该系列涵盖一系列时间范围 - 例如有的只用一年,有的只用几个月。我希望生成的图表为每个系列绘制一条线,每条线仅在该系列涵盖的时间范围内可见。

图表后面的数据是数据框 (meltdf2) 的格式,包含 4 列 - 月份、用户、分数和风险。

简化版本是:

Month   user   score   risk
jan-18  A      1       high
feb-18  A      1       high
mar-18  A      2       mid
apr-18  A      1       high
feb-18  B      1       high
mar-18  B      2       mid
apr-18  B      3       low
mar-18  C      3       low
apr-18  C      3       low

目前,图表显示三行,每个用户一行,每行覆盖图表的全部内容。 理想情况下,我将有一个图表,其线 A 将跨越图表的整个宽度,而线 BC 将仅跨越图表的一部分。

我已尝试包含 BC 未涵盖的月份的 NA 值,但它们的线仍跨越整个图表。由于 NA 值路由失败,我尝试在一行上手动设置多种颜色,但这似乎不起作用。

我目前使用的代码如下:

#create colour palette based on discrete risk levels - used to specify manual colour scale in plot.
pal <- c("High"="red2","Mid"="gold","Low" = "limegreen","NA"= "NA")

#create plot with line and points.
#colour of points based on colour column of meltdf2
ggplot(data = meltdf2, aes(x = Month, y = user, group = user)) +
  geom_line(linetype = "dashed", colour = "grey") +
  geom_point(aes(colour = meltdf2$risk, size = 3)) +
  scale_colour_manual(values = pal, limits = names(pal)) +
  scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
        axis.line.x = element_line(colour = "darkgrey"),
        panel.background = element_rect(fill = "white"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank())

此代码生成以下图表:

理想情况下,不会显示每个系列的第一个数据点之前的每条灰色虚线的部分。

【问题讨论】:

  • 我无法用您提供的数据的 sn-p 重现您的问题。此外,根据列名/ ggplot 参数,您的数据 sn-p 似乎不是您提供给 ggplot 的 data.frame,所以这也令人困惑。我最好的猜测是ggplot(df, aes(Month, score, group = user)) + geom_line() + geom_point(aes(colour = colour)) + scale_colour_identity()
  • @teunbrand 我对这个问题做了一些修改——希望现在更清楚了

标签: r ggplot2 plot


【解决方案1】:

已通过修改图表后面的数据框 (meltdf2) 解决了此问题。使用na.omit(meltdf2) 删除了每个系列不存在数据的行,并阻止了该线的绘制。 最终结果如下:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多