我有一个带有彩色背景(geom_rect)和彩色线(geom_line)的图。我试图保持一致的图例顺序:o2 高于温度,或温度高于 o2。关键是一致性。
我尝试使用 guides(col = guide_legend(order = 2), fill = guide_legend(order = 1)) 并且这改变了顺序但也将图例的样式完全从渐变更改为一系列特定值。
如何在保持图例的渐变配色方案的同时设置顺序?更改 ggplot 调用中代码的位置不会改变结果。
legend_t = parse(text='"Temperature ("^o*"C)" ')
legend_o2 = parse(text='"DO2 (mmol m" ^-3*")" ')
ggplot() +
geom_rect(data = rects, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = o2_fill),
inherit.aes = FALSE, alpha = 0.5) +
scale_fill_gradient(low = "yellow", high = "red", na.value = NA, limits = c(30,250)) +
geom_line(data = plot, aes(x = tf/60, y = Depth*-1, col = Temperature), size = 2) +
scale_colour_gradient(low = "blue", high = "red", na.value = NA, limits = c(3,30)) +
labs(fill = legend_o2) +
labs(col = legend_t) +
xlab("Dive Duration (minutes)") + ylab("Depth (meters)") +
#scale_y_continuous(limits = c(-1600,0), breaks=seq(-1600,0,100)) + # sets axis tick marks on y axis scale
#scale_x_continuous(limits = c(0,round_any(max(dive$tf/60),10, f = ceiling)), breaks=seq(0,round_any(max(dive$tf/60),10, f = ceiling),5)) +
#coord_cartesian(ylim = c(-1300,0)) + #zooms in so the coloured background doesn't get cut off
guides(col = guide_legend(order = 2), fill = guide_legend(order = 1)) #set legend order
这是使用指南的结果:图例顺序一致但样式完全改变 为了重现,我在缩放和缩放上加上了一些#,这是数据的一个小样本:
> print(rects[c(1:10),])
xmin xmax ymin ymax o2_fill
1 -Inf Inf 0.000000 -0.505760 200.7229
2 -Inf Inf -0.505760 -1.555855 200.7229
3 -Inf Inf -1.555855 -2.667682 200.7930
4 -Inf Inf -2.667682 -3.856280 200.8371
5 -Inf Inf -3.856280 -5.140361 200.8713
6 -Inf Inf -5.140361 -6.543034 200.9002
7 -Inf Inf -6.543034 -8.092519 200.9263
8 -Inf Inf -8.092519 -9.822750 200.9506
9 -Inf Inf -9.822750 -11.773680 200.9745
10 -Inf Inf -11.773680 -13.991040 201.0089
> print(plot[c(1:10),])
Date_time Depth Temperature DeepDiveNo tf o2
1: 2016-06-08 10:54:00 9.5 29.15 1 4815 200.9745
2: 2016-06-08 09:33:45 10.5 29.15 1 0 200.9745
3: 2016-06-08 09:34:00 13.5 28.85 1 15 201.0697
4: 2016-06-08 10:53:45 14.5 28.95 1 4800 201.0697
5: 2016-06-08 10:53:30 18.5 28.20 1 4785 204.0405
6: 2016-06-08 09:34:15 19.0 28.15 1 30 204.0405
7: 2016-06-08 10:53:15 23.5 27.35 1 4770 208.8913
8: 2016-06-08 09:34:30 24.5 27.20 1 45 208.8913
9: 2016-06-08 10:53:00 27.0 27.15 1 4755 210.4293
10: 2016-06-08 09:34:45 28.0 27.15 1 60 210.4293