将ggplot图例更改为离散而不是连续

时间:2020-07-25 19:21:24

标签: r ggplot2

如何修复图例,使其不连续缩放?我想说的是,黑线表示拟合值,蓝线表示预测值。

enter image description here

代码:

df_pred <- data.frame(
        year = c("2011","2012","2013","2014","2015","2016","2017","2018","2019","2020","2021","2022","2023"),
        values = c(0.8888866, 0.8716710, 0.8447683, 0.8274719, 0.8321376, 0.8361800, 0.8319212, 0.8325700, 0.8551733, 0.8832598, 0.9072822, 0.9267712, 0.9424237),
        upper = c(rep(NA,10),0.9827305, 0.9919751, 0.9964064),
        lower = c(rep(NA,10),0.6272399, 0.5644133, 0.4914222),
        group = c(1,1,1,1,1,1,1,1,1,1,2,2,2))

ggplot(df_pred,aes(x=year, y=values, group=1, colour = group))+
  geom_line()+geom_point()+
  geom_ribbon(data=df_pred,aes(x = c(1,2,3,4,5,6,7,8,9,10,11,12,13) ,ymin = lower, ymax = upper), inherit.aes = FALSE,fill = "lightblue", alpha=0.3)+ labs(y="Probability of sub-specialism", x = "Year")+ theme(axis.title.x = element_text( size = 14),axis.title.y = element_text(size =14)) +theme(legend.position="bottom")+
  theme(legend.title=element_blank())#+ scale_color_manual(values=c("black","blue"))

1 个答案:

答案 0 :(得分:0)

您可以将列组设置为一个因素,

df_pred$group <- as.factor(df_pred$group)

并更改组名(1 =已拟合,2 =预测),

df_pred$group <- ifelse(df_pred$group == 1, 'fitted', 'predicted')

然后再次运行您的代码。

enter image description here