ggplot:将线轮廓添加到散点图

时间:2019-12-04 12:12:01

标签: r ggplot2 scatter-plot

几天来,我在10分钟的时间戳中有成千上万个数据点。 绘制散点图会创建一个重复的图案,我想强调一下。 enter image description here 在上图中,我想画一条线,概述此散点图的形状。更具体地说,每value个滴答经过hour最大值的一行。 我试过添加freqpolyhist之类的内容,但它们不适合此图类型(其中x为时间戳)。我也尝试过计算每个时间戳的最大值,但是由于原始数据是高格式(每个时间戳都有多个条目),所以我不能在同一个锅中使用此最大值。

示例数据:

set.seed(999)
df <- data.frame('hour' = rep(seq(ISOdatetime(2019,12,1,0,0,0), by = '10 mins', length.out = 6), 3),
                 'value' = rnorm(18),
                 'category' = rep(c('a', 'b', 'c'), 6))

ggplot(df, aes(x = hour, y = value)) +
  geom_point(aes(color = category), cex = 7) +
  theme_minimal()

这就是我希望最终产品的外观(手工添加的黑线): enter image description here

1 个答案:

答案 0 :(得分:3)

您可以通过将geom_point的美感移到实际参数中来实现。然后,您可以添加stat_summary来添加行,如下所示:

set.seed(999)
library(ggplot2)

df <- data.frame('hour' = rep(seq(ISOdatetime(2019,12,1,0,0,0), by = '10 mins', length.out = 6), 3),
                 'value' = rnorm(18),
                 'category' = rep(c('a', 'b', 'c'), 6))

# Valid for ggplot2 version 3.2.1.9000
# fun.y might be needed if running an earlier version
ggplot(df) +
  geom_point(aes(x = hour, y = value, color = category), cex = 7) +
  theme_minimal()+
  stat_summary(geom = "line", fun = max, aes(hour, value))

# Or you can simplify a little and just keep the color aesthetic in the geom_point
# Same result achieved

ggplot(df, aes(x = hour, y = value),) +
  geom_point( aes(color = category), cex = 7) +
  stat_summary(geom = "line", fun = max)+
  theme_minimal()

这允许您添加线,然后将摘要统计信息添加为新的“线”几何。

points with line through max

相关问题