【发布时间】:2019-12-04 14:24:29
【问题描述】:
我想创建一个包含多个min 和max 点的图表,这些点按month 和year 分组。
我的数据集trythis3:
structure(list(Month = structure(c(5L, 4L, 3L, 2L, 1L, 2L, 3L,
4L), .Label = c("Feb", "Apr", "Jun", "Aug", "Oct"), class = "factor"),
Year = c(1994L, 1995L, 1996L, 1997L, 1998L, 2003L, 2007L,
2011L), Temperature = c(10.1717660661212, 19.1113251384721,
14.80103145439, 8.59164858808079, 6.86800188715349, 9.55507283803179,
15.6577982450023, 16.25518817037), color = c(FALSE, FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, TRUE), color1 = c(FALSE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)), row.names = c(NA,
-8L), groups = structure(list(Year = c(1994L, 1995L, 1996L, 1997L,
1998L, 2003L, 2007L, 2011L), .rows = list(1L, 2L, 3L, 4L, 5L,
6L, 7L, 8L)), row.names = c(NA, -8L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
以data.frame 的身份对此进行调查:
Month Year Temperature color color1
<fct> <int> <dbl> <lgl> <lgl>
1 Oct 1994 10.2 FALSE FALSE
2 Aug 1995 19.1 FALSE FALSE
3 Jun 1996 14.8 FALSE FALSE
4 Apr 1997 8.59 FALSE FALSE
5 Feb 1998 6.87 FALSE FALSE
6 Apr 2003 9.56 FALSE FALSE
7 Jun 2007 15.7 FALSE FALSE
8 Aug 2011 16.3 TRUE FALSE
我是如何计算 col 和 color 和 color1 的,它们是变量 Month 和 Year 的 min 和 max 值:
trythis1 <- prac1 %>%
group_by(Month) %>%
mutate(color = (min(Temperature) == Temperature | max(Temperature) == Temperature))
trythis2 <- prac1 %>%
group_by(Year) %>%
mutate(color = (min(Temperature) == Temperature | max(Temperature) == Temperature))
trythis3 <- cbind(trythis1, trythis2)
trythis3 <- trythis3[, c(-5, -6, -7)]
data.frameprac1 的示例:
Month Year Temperature
1 Jan 1994 5.11379276
2 Feb 1994 3.21683318
3 Mar 1994 7.78435180
4 Apr 1994 8.37781038
5 May 1994 10.97117575
6 Jun 1994 15.06396991
7 Jul 1994 19.06792551
8 Aug 1994 16.84395137
9 Sep 1994 13.28449477
10 Oct 1994 10.17176607
11 Nov 1994 9.87512853
12 Dec 1994 6.23880411
13 Jan 1995 4.39990197
14 Feb 1995 6.37256581
15 Mar 1995 5.57871938
16 Apr 1995 9.09780864
17 May 1995 11.83570263
18 Jun 1995 13.85246862
19 Jul 1995 19.19339040
20 Aug 1995 19.11132514
21 Sep 1995 13.90945926
我认为它如何与这段代码一起工作:
ggplot(trythis3, aes(x = Month, Temperature, group = Year)) + geom_line() + geom_point(aes(color = color)) + geom_point(aes(color = color1)) + facet_wrap(~Year) + scale_color_manual(values = c(NA,c("red", "blue")))
【问题讨论】:
-
为绘图使用两个数据框。线使用
prac1,点图层使用长格式数据,其中一列表示“类型”,值为“最大月”、“最小月”和“最大年”。 -
我认为这里缺少的一件事是制作您对映射感兴趣的类别。您有 5 个要为其设置颜色的类别(如果您计算 NA),但您只创建了两个类别(TRUE 和 FALSE)。你可以用
case_when()(或嵌套的ifelse())来做到这一点。