繁体   English   中英

将图例添加到覆盖在 geom_boxplot 上的 geom_point

[英]Add a legend to geom_point overlaid on geom_boxplot

所以我创建了一个数据箱线图,然后在该数据上添加了一个设定点。 我希望我的图例能够捕获 geom_points 代表的数据类型。 谢谢!


ggplot(data = NULL) +
 geom_boxplot(data = discuss_impact_by_county,
              aes(x=reorder(State,discuss, FUN = median),y=discuss),
              outlier.shape = NA) +
 theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
 labs(x = "States") +
 geom_point(data = by_state, 
            aes(x = State, y = discuss_happen_difference), 
            col = "red", 
            size = 3,
            show.legend = TRUE)

如果你想要一个传奇,你必须在美学上 map。 在你的情况下 map color aes 上的东西,即将col="red"移动到aes()并使用scale_color_manual设置值和图例 label 分配给颜色 label "red"

因为你只有一个“类别”的点,你可以简单地做scale_color_manual(values = "red", label = "We are red points")来设置颜色和 label。如果你有多个不同的点 colors 最好使用命名向量将 colors 和图例标签分配给正确的“颜色标签”,即使用scale_color_manual(values = c(red = "red"), label = c(red = "We are red points"))

使用一些随机示例数据试试这个:

library(ggplot2)
library(dplyr)

set.seed(42)
discuss_impact_by_county <- data.frame(
  State = sample(LETTERS[1:4], 100, replace = TRUE),
  discuss = runif(100, 1, 5)
)

by_state <- discuss_impact_by_county %>% 
  group_by(State) %>% 
  summarise(discuss_happen_difference = mean(discuss))
#> `summarise()` ungrouping output (override with `.groups` argument)

ggplot(data = NULL) +
  geom_boxplot(data = discuss_impact_by_county,
               aes(x=reorder(State,discuss, FUN = median),y=discuss),
               outlier.shape = NA) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
  labs(x = "States") +
  geom_point(data = by_state, 
             aes(x = State, y = discuss_happen_difference, col = "red_points"), 
             size = 3,
             show.legend = TRUE) +
  scale_color_manual(values = "red", label = "We are red points")

暂无
暂无

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

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