给出以下示例数据框:
library(ggplot2)
set.seed(1234)
Site <- c("Blue", "Blue", "Blue", "Blue", "Red", "Red", "Red", "Red", "Green", "Green", "Green", "Green")
Time <- as.POSIXct(c("2019-10-01", "2019-10-10", "2019-11-10", "2019-11-12", "2019-12-12", "2019-12-20", "2019-12-22", "2019-12-25", "2019-12-01", "2019-12-10", "2019-12-12", "2019-12-22"))
DepNum <- jitter(c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2))
SS <-c("Start", "Stop", "Start", "Stop", "Start", "Stop", "Start", "Stop", "Start", "Stop", "Start", "Stop")
DF <- data.frame(Site, Time, DepNum, SS)
我想用DepNum变量绘制线形图,但是然后添加第二列(SS)可以着色的点。
ggplot(DF, aes(x = Time, y = DepNum)) +
geom_line(aes(color = Site)) +
geom_point(aes(color = SS))
当我进行以上绘制时,“开始”和“停止”以图例结尾。我想避免“ SS”变量以图例结尾(但保留“ DepNum”图例)。我还想指定点的颜色(又称-“开始”点为绿色,“停止”点为红色)。
研究了这些问题之后,我找到了包含以下内容的答案:geom_point(aes(col = SS), show.legend = FALSE)
。但这似乎不起作用:
ggplot(DF, aes(x = Time, y = DepNum)) +
geom_line(aes(color = Site)) +
geom_point(aes(color = SS), show.legend = FALSE)
答案 0 :(得分:1)
您要的内容需要具有不同映射的两个不同的色标。这在ggplot2中是不可能的,但可以使用扩展包ggnewscale来完成。它提供了new_scale_color()
函数,可让您使用其自己的映射和图例参数定义一个完全独立的第二色标。
library(ggplot2)
library(ggnewscale)
set.seed(1234)
Site <- c("Blue", "Blue", "Blue", "Blue", "Red", "Red", "Red", "Red", "Green", "Green", "Green", "Green")
Time <- as.POSIXct(c("2019-10-01", "2019-10-10", "2019-11-10", "2019-11-12", "2019-12-12", "2019-12-20", "2019-12-22", "2019-12-25", "2019-12-01", "2019-12-10", "2019-12-12", "2019-12-22"))
DepNum <- jitter(c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2))
SS <-c("Start", "Stop", "Start", "Stop", "Start", "Stop", "Start", "Stop", "Start", "Stop", "Start", "Stop")
DF <- data.frame(Site, Time, DepNum, SS)
ggplot(DF, aes(x = Time, y = DepNum)) +
geom_line(aes(color = Site)) +
scale_color_manual(
values = c(Blue = "blue", Red = "red", Green = "green")
) +
new_scale_color() +
geom_point(aes(color = SS), show.legend = FALSE) +
scale_color_manual(
values = c(Start = "green", Stop = "red")
)
由reprex package(v0.3.0)于2019-11-02创建