如何在ggplot中将图例放入双y轴

时间:2019-08-05 22:22:34

标签: r ggplot2

我正在使用ggplot绘制图表,但是我不知道如何在图例中添加图例。据我所知,它应该是自动的,但是显然我缺少了一些东西。这是我的代码:

ggplot(data = df_SZ, aes(y=Bottom90, x = year) ) +
  geom_line(aes(y= Bottom90, colour = "Bottom [%90]"), colour = "dodgerblue4") + 
  ylab("Bottom 90 %") +
  geom_line(aes(y = Top10/2, colour = "Top [%10]"), colour = "dodgerblue2")+
  scale_y_continuous(sec.axis = sec_axis(~.*2, name = "Top 10%"))+
  theme_minimal()

有人可以帮助我介绍此图产生的每个时间序列的图例吗?

以下是再现图表的数据:

structure(list(year = c(1980, 1981, 1982, 1983, 1984, 1985, 1986, 
1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 
2009, 2010, 2011, 2012), Bottom90 = c(0.331616, 0.335162, 0.341236, 
0.348128, 0.354806, 0.358124, 0.357456, 0.355754, 0.351654, 0.347886, 
0.342204, 0.337964, 0.333678, 0.32993, 0.324861995101929, 0.321839992824554, 
0.318419989997864, 0.314135990222931, 0.309657990932465, 0.307315993309021, 
0.306488001346588, 0.306282007694244, 0.305374002456665, 0.305185997486115, 
0.302269995212555, 0.297027993202209, 0.286311984062195, 0.276103985309601, 
0.26451199054718, 0.253880000114441, 0.242681992053986, NA, NA
), Top10 = c(0.668384, 0.664838, 0.658764, 0.651872, 0.645194, 
0.641876, 0.642544, 0.644246, 0.648346, 0.652114, 0.657796, 0.662036, 
0.666322, 0.67007, 0.675138004898071, 0.678160007175446, 0.681580010002136, 
0.685864009777069, 0.690342009067535, 0.692684006690979, 0.693511998653412, 
0.693717992305756, 0.694625997543335, 0.694814002513885, 0.697730004787445, 
0.70297200679779, 0.713688015937805, 0.723896014690399, 0.73548800945282, 
0.746119999885559, 0.757318007946014, NA, NA)), row.names = c(NA, 
-33L), na.action = structure(c(`1` = 1L, `2` = 2L, `3` = 3L, 
`4` = 4L, `101` = 101L, `102` = 102L, `103` = 103L, `104` = 104L, 
`105` = 105L, `106` = 106L, `107` = 107L), class = "omit"), class = c("tbl_df", 
"tbl", "data.frame"))

1 个答案:

答案 0 :(得分:1)

colour之外提供aes时,ggplot不会在图上放置图例。在保留图例的同时更改颜色的正确方法是使用scale_color_...scale_fill_...函数。对于这种情况,我使用了scale_color_manual

library(ggplot2)

ggplot(data = df_SZ, aes(y=Bottom90, x = year) ) +
  geom_line(aes(y= Bottom90, colour = "Bottom [%90]")) + 
  ylab("Bottom 90 %") +
  geom_line(aes(y = Top10/2, colour = "Top [%10]"))+
  scale_y_continuous(sec.axis = sec_axis(~.*2, name = "Top 10%"))+
  theme_minimal() +
  scale_color_manual(name = "Legend", labels = c("Bottom [%90]","Top [10%]"), 
                     values = c("dodgerblue4", "dodgerblue2"))