我想要实现的是,图例的标题为“年”,蓝色条显示为“ 2016”的小矩形,圆圈和三角形显示“ 2012”和“ 2008”的年。有什么想法可以实现吗?因为现在我只获得图例数据的图例。
可复制的示例:
# packages needed
library(tidyverse)
library(eurostat)
library(lubridate)
# downlaoding the dataset
ilc_di11 <- get_eurostat("ilc_di11", stringsAsFactors=FALSE)
# manipulating data
df <- ilc_di11 %>% filter(age=="TOTAL",
geo %in% c("EU28", "BE","BG","CZ","DK","DE","EE","IE","EL","ES","FR","HR","IT","CY","LV","LT","LU","HU","MT","NL","AT","PL","PT","RO","SI","SK","FI","SE","UK"),
sex=="T",
year(time) %in% c("2008", "2012", "2016"))%>%
spread(time, values) %>%
rename(`2008`=`2008-01-01`,
`2012`=`2012-01-01`,
`2016`=`2016-01-01`)%>%
gather(var, values, 5:6)
# plotting data
ggplot(data=df)+
geom_bar(aes(x=reorder(geo, `2016`), y=`2016`),
stat = "identity",
position = "dodge",
fill="steelblue")+
geom_point(aes(x=reorder(geo, `2016`), y=values,
shape=var,
color=var),
size=3)+
labs(title="Pajamų nelygybė nustatyta pagal S80/S20 santykį",
subtitle="Šaltinis: Eurostat (ilc_di11)",
x="Šalys",
y="Santykis")
答案 0 :(得分:2)
有许多解决方案,其中之一就是将虚拟data.frame
传递到单独的geom_point
层。将此点的大小设置为0,这样它就不会显示在绘图中,而是为其指定颜色和形状。
ggplot(df, aes(shape = var, color = var)) +
geom_bar(aes(reorder(geo, `2016`), `2016`),
stat = "identity", position = "dodge", fill = "steelblue", color = NA) +
geom_point(aes(x, y),
data.frame(x = Inf, y = Inf, var = "2016", var = "2016"),
size = 0) +
geom_point(aes(reorder(geo, `2016`), values, shape = var, color = var),
size = 3) +
labs(title = "Pajamų nelygybė nustatyta pagal S80/S20 santykį",
subtitle = "Šaltinis: Eurostat (ilc_di11)",
x = "Šalys",
y = "Santykis",
color = "Year",
shape = "Year")