繁体   English   中英

在R中的多面ggplot2图形中突出显示最小和最大点

[英]Highlight minimum and maximum points in faceted ggplot2 graph in R

我正在使用R中的内置economics (来自ggplot2软件包)数据集,并使用以下代码为同一图中的每个变量绘制了时间序列:

library(reshape2)
library(ggplot2)

me <- melt(economics, id = c("date"))
ggplot(data = me) + 
     geom_line(aes(x = date, y = value)) +
     facet_wrap(~variable, ncol = 1, scales = 'free_y')

现在,我进一步想细化图表,对于每个系列,我都希望显示一个最小和最大值的红点。 所以我想,如果我可以找到每个时间序列的最大值和最小值的坐标,那么我可以找到一种在每个时间序列的起点和终点绘制红点的方法。 为此,我使用了以下代码:

which(pce == min(economics$pce), arr.ind = TRUE) 
which(pca == max(pca), arr.ind = TRUE)

这真的没有带我到任何地方。 谢谢:)

方法1:使用联接

当您要保存过滤的子集时,这可能会很好


library(reshape2)
library(ggplot2)
library(dplyr)

me <- melt(economics, id=c("date"))

me %>%
  group_by(variable) %>%
  summarise(min = min(value),
            max = max(value)) -> me.2

left_join(me, me.2) %>%
  mutate(color = value == min | value == max) %>%
  filter(color == TRUE) -> me.3

ggplot(data=me, aes(x = date, y = value)) + 
  geom_line() +
  geom_point(data=me.3, aes(x = date, y = value), color = "red") +
  facet_wrap(~variable, ncol=1, scales='free_y')

方法2:简化无联接

谢谢@格雷戈

me.2 <- me %>%
  group_by(variable) %>%
  mutate(color = (min(value) == value | max(value) == value))

ggplot(data=me.2, aes(x = date, y = value)) +
  geom_line() +
  geom_point(aes(color = color)) +
  facet_wrap(~variable, ncol=1, scales="free_y") +
  scale_color_manual(values = c(NA, "red"))

情节

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM