首页 文章

ggplot自定义geom_point形状的图例并删除背景

提问于
浏览
1

我的数据看起来像这样:

df = data.frame(
  measure = c("Measure A","Measure B","Measure C","Measure D",
              "Measure E","Measure F","Measure G"),
  overall = c(56, 78, 19, 87, 45, 51, 19),
  company = c(45, 89, 18, 98, 33, 55, 4),
  company_p = c(32, 65, 5, 56, 12, 45, 10)
)

使用此代码:

ggplot(df %>% 
         mutate(fill = ifelse(overall > company, " Below Overall  "," Above Overall  ")), 
       aes(measure)) + 
  geom_col(aes(y=company, fill= fill)) + 
  geom_point(aes(y=overall, color="overall"), size=6, shape=124) + 
  geom_point(aes(y=company_p, color="company_p"), size=2, shape=19) +
  coord_flip() + 
  scale_color_manual(values=c("red4","grey3"),labels=c("Company Last Year","Overall")) + 
  scale_fill_manual(values=c(" Below Overall  "="lightpink2",
                             " Above Overall  "="lightblue2")) +
  theme(legend.key=element_blank())

我得到一个如下图:

enter image description here

如何设置图例以使图例中的company_p值或“公司去年”看起来像相应的形状,而整体看起来像黑线?

我尝试将形状类型链接到图例,如下所示:

ggplot(df %>% 
         mutate(fill = ifelse(overall > company, " Below Overall  "," Above Overall  ")), 
       aes(measure)) + 
  geom_col(aes(y=company, fill= fill)) + 
  geom_point(aes(y=overall, color="overall"), size=6, shape="overall") + 
  geom_point(aes(y=company_p, color="company_p"), size=2, shape="company_p") +
  coord_flip() + 
  scale_shape_manual(values=c(overall=124, company_p=19)) +
  scale_color_manual(values=c("red4","grey3"),labels=c("Company Last Year","Overall")) + 
  scale_fill_manual(values=c(" Below Overall  "="lightpink2",
                             " Above Overall  "="lightblue2")) +
  theme(legend.key=element_blank())

enter image description here

但是形状符号与参考不相关(124是|,19是圆),并且看起来形状在图例中是一起的,而不是分开的 .

1 回答

  • 1

    这是一种方法 . 我使用 tidyr 重新整形了数据,以便将两个列合并在一起 . 由于您需要具有不同颜色,大小和形状的点,因此需要在 aes() 中包含 geom_point 中的所有点,然后您可以使用具有相同 name 参数的 scale_ 函数 . 我把它命名为 Legend ,但你可以把它改成任何有意义的东西 .

    library(tidyr)
    df2 <- df %>% mutate(fill = ifelse(overall > company, " Below Overall  "," Above Overall  ")) %>%
      gather(key, val, -company, -measure, -fill)
    
    ggplot(df2, aes(measure)) + 
      geom_col(aes(y=company, fill= fill), data = df2[!duplicated(df2$measure),]) +
      scale_fill_manual(values=c(" Below Overall  "="lightpink2"," Above Overall  "="lightblue2")) +
      geom_point(aes(y=val, shape=key, color = key, size = key), data = df2) +
      scale_color_manual(name = "Legend", values=c("red4", "grey3"), labels = c("Company Last Year", "Overall")) +
      scale_shape_manual(name = "Legend", values = c(19, 124), labels = c("Company Last Year", "Overall")) +
      scale_size_manual(name = "Legend", values = c(2, 6), labels = c("Company Last Year", "Overall")) +
      coord_flip()
    

    enter image description here

相关问题