Если вы установите две разные эстетики для связи с одним и тем же столбцом в наборе данных, ggplot
попытается объединить легенды, но эта ссылка будет разорвана, если вы измените какой-либо элемент легенды одного без корректировки другого. Это означает, что вам также необходимо обратиться к легенде fill=
, если вы меняете заголовок colour=
легенды:
labs(colour = "Estrato", fill = "Estrato")
Чтобы объяснить, почему, вот образец набора данных и графика:
set.seed(1234)
df <- data.frame(
x=rep(1:10,4),
y=c(rnorm(10,0,0.05), rnorm(10,0.05,0.01),rnorm(10,-0.15,0.05),rnorm(10,0.2,0.05)),
type=c(rep('A',10),rep('B',10),rep('C',10),rep('D',10))
)
p <- ggplot(df, aes(x,y, color=type, fill=type)) +
geom_line() +
geom_ribbon(aes(ymin=y-0.02, ymax=y+0.02),alpha=0.2, color=NA)
p
You can see in the above plot that both fill=
and color=
are linked to df$type
, and the legend created combines those two. However, there are still two legends, but both are combined. If you think of it this way, then that means when you change the title of one, it will now force ggplot
to separate the legends:
p + labs(color='My_colors')
The solution is pretty simple: just make the same change to both legends.
p + labs(color='My_colors', fill='My_colors')
введите описание изображения здесь
Кстати, это также верно и для других настроек легенды, например, с метками. Это означает, что если вы вносите изменения, используя scale_color_manual()
, вам, вероятно, понадобится scale_fill_manual()
, чтобы собрать их вместе.