如何在ggplot的双y轴上放置图例

msh855

我正在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"))
米--

当您colour在 之外提供aesggplot不会在图表上放置图例。在保留图例的同时更改颜色的正确方法是使用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"))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章