0

所以我创建了一个数据箱线图,然后在该数据上添加一个设定点。我希望我的图例能够捕获 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)
4

1 回答 1

0

如果你想要一个传奇,你必须在美学上进行映射。在您的情况下,在 aes 上映射一些东西color,即移入col="red"aes()用于scale_color_manual设置要分配给颜色标签的值和图例标签"red"

由于您只有一个“类别”的点,您可以简单scale_color_manual(values = "red", label = "We are red points")地设置颜色和标签。如果您有多个不同颜色的点,最好使用命名向量将颜色和图例标签分配给正确的“颜色标签”,即使用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")

于 2020-10-24T07:51:14.680 回答