我有这个箱线图,然后我试图在它上面绘制两个不同颜色的不同点,以便用户可以看到它们落在箱线图上的位置,并将它们相互比较。问题是,我希望图例显示两个带有相应颜色的点及其ID。相反,图例显示了boxplot类别/颜色。如何覆盖图例以仅显示我想要的内容?这是我的代码:
library(datasets)
library(ggplot2)
data(airquality)
airquality$Month <- factor(airquality$Month,
labels = c("May", "Jun", "Jul", "Aug", "Sep"))
airquality$ID <-seq(1:nrow(airquality))
dataPoint <- airquality[11,]
dataPoint2 <- airquality[17,]
plt <- ggplot(airquality, aes(x = Month, y = Ozone, color = Month)) +
geom_boxplot(show.legend=TRUE,outlier.shape = NA) +
geom_point(data = dataPoint, color='darkblue', aes(x = Month, y = Ozone), size = 3,show.legend=TRUE) +
geom_point(data = dataPoint2, color='darkred', aes(x = Month, y = Ozone), size = 3,show.legend=TRUE) +
theme(legend.position = "bottom")
plt
答案 0 :(得分:2)
我会通过将点映射到不同的美学来实现这一点。如果show.legend
在这种情况下设置为FALSE
,那么图例将单独显示。您还可以映射到点形状或任何其他美学。或者,您可以映射boxplot geom的fill
,并映射点geom的color
。
例如:
library(datasets)
library(ggplot2)
data(airquality)
airquality$Month <- factor(airquality$Month,
labels = c("May", "Jun", "Jul", "Aug", "Sep"))
airquality$ID <-seq(1:nrow(airquality))
points <- c(11, 17)
airquality$Points <- NA
airquality$Points[points] <- c("Point a", "Point b")
plt <- ggplot(airquality, aes(x = Month, y = Ozone, color = Month)) +
geom_boxplot(outlier.shape = NA) +
geom_point(data = airquality[!is.na(airquality$Points), ],
mapping=aes(x = Month, y = Ozone, fill = Points), size = 3, shape = 21, inherit.aes=FALSE) +
theme(legend.position = "bottom")
plt
答案 1 :(得分:2)
最简单的绘制图形的方法是:
dataPoint
个数据集(使用rbind
)。像这样你只需要拨打一个geom_point
scale_color_manual
代码:
# Combine datasets
dataPoints <- rbind(dataPoint, dataPoint2)
# Plot
ggplot(airquality, aes(Month, Ozone, fill = Month)) +
geom_boxplot(outlier.shape = NA) +
geom_point(data = dataPoints,
aes(Month, Ozone, color = factor(ID)),
size = 3) +
labs(color = "ID",
fill = "Month") +
scale_color_manual(values = c("darkblue", "darkred")) +
theme(legend.position = "bottom")
结果:
PS:我不会为月份(填充)添加调色板,因为此信息已经显示在x轴上(冗余信息)。要删除填充图例,您可以添加guides(fill = FALSE)
。
在OP评论后编辑以使用形状:
如果你想要形状而不是颜色
ggplot(airquality, aes(Month, Ozone, fill = Month)) +
geom_boxplot(outlier.shape = NA) +
geom_point(data = dataPoints,
aes(Month, Ozone, shape = factor(ID)),
size = 3) +
labs(shape = "ID",
fill = "Month") +
scale_shape_manual(values = c(15, 17)) +
theme(legend.position = "bottom")