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

时间:2018-05-16 21:36:46

标签: r ggplot2

我的数据看起来像这样:

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

如何设置图例以便公司_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 个答案:

答案 0 :(得分:1)

这是一种方法。我使用tidyr重新整理了数据,以便将两个列合并在一起。由于您需要具有不同颜色,大小和形状的点,因此您需要在aes() geom_point中包含所有这些点,然后您可以使用scale_函数使用相同的name Legend 1}}参数。我将其命名为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() ,但您可以将其更改为任何有意义的内容。

pyuic5 test29.ui -o test29.pi

enter image description here