我有看起来像这样的数据:
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())
我得到一个图,看起来像这样:
如何设置图例,以使图例上的company_p值或“ Company Last Year”看起来像相应的形状,而“ Total”看起来像黑线?
我尝试将形状类型链接到图例,如下所示:
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())
但是形状符号与参考没有关联(124是|,19是一个圆形),并且看起来这些形状在图例中在一起,而不是分开。
这是一种方法。我重塑了数据tidyr
以合并有争议的两列。由于您希望这些点具有不同的颜色,大小和形状,因此需要在aes()
for中包括所有这些点geom_point
,然后可以使用scale_
具有相同name
参数的函数。我命名了,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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句