如何从geom_point中删除图例并将两条平滑线的线型图例移至图形内部

我有数据框df

df<- data.frame(C.D=c(5,5,10,20,40,80,100,130,160,190,220,250,280,310,340,359,359),activity=c(1.1,1.6,0.6,1.2,1.8,1.3,1.4,1.88,0.99,2.1,1.75,1.5,2.4,1.55,0.9,3.2,1.7,3.8,2.8,3.9,3.4,2.6,4.1,2.3,3.6,4.3,3.0,2.5,1.1,0.5,0.8,1.5),C.I=c(0.05,0.21,0.11,0.2,0.15,0.28,0.24,0.18,0.33,0.22,0.13,0.16,0.31,0.23,0.36,0.25,0.58,0.42,0.52,0.82,0.71,0.64,0.51,0.4,0.54,0.55,0.68,0.32,0.37,0.04,0.12))

df

   C.D activity  C.I
1    5     1.10 0.05
2    5     1.60 0.21
3    5     0.60 0.11
4   10     1.20 0.20
.    .       .    .
.    .       .    .
.    .       .    . 

我还具有下面显示的代码,用于根据数据框df创建图形。

ggplot(df,aes(C.D,activity)) +
  geom_point(aes(C.D,activity,color = C.I)) + 
  scale_colour_gradientn(colours=c("green","black")) + 
  theme_bw() + 
  geom_smooth(aes(linetype = "activity"))  +
  ggtitle("activity ~ Current Direction 20 meters") +
  theme(plot.title = element_text(hjust = 0.5)) +
  geom_smooth(aes(C.D,C.I * 6,linetype = "C.I."),se=FALSE,colour = "red",show.legend = TRUE) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . / 6,name = "CI")) +
  scale_linetype_manual(
    values = c(1,1),guide = guide_legend(override.aes = list(colour = c("blue","red")))
  )

如何从geom_point中删除图例并将两条平滑线的线型图例移至图形内部

但是,我想与grid.arrange(4x4)一起布置多个图,并且需要从右侧删除所有图例。我想删除相对于代码行geom_point(aes(C.D.4m,VeDBA,color = C.I.4m))的图例,并将关于linetype的图例移到图形的insede(中上侧)。

如果我尝试theme(legend.position='none'),则会删除两个图例。我该如何相对于我在geom_point中上色的方式删除图例,并将相对于linetype的图例移动到图的内部?

asdfghjklqwertyumnb 回答:如何从geom_point中删除图例并将两条平滑线的线型图例移至图形内部

您应该使用guide = FALSE中的scale_colour_continous摆脱颜色图例,然后使用legend.justificationlegend.position移动线型图例。

因此,对于您的情节,您应该执行以下操作:

ggplot(df,aes(C.D,Activity)) +
  geom_point(aes(C.D,Activity,color = C.I)) + 
  scale_colour_gradientn(colours=c("green","black")) + 
  theme_bw() + 
  geom_smooth(aes(linetype = "Activity"))  +
  ggtitle("Mean activity as a function of C.D.20m for winter from hourly data") +
  theme(plot.title = element_text(hjust = 0.5)) +
  geom_smooth(aes(C.D,C.I * 6,linetype = "C.I."),se=FALSE,colour = "red",show.legend = TRUE) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . / 6,name = "CI")) +
  scale_linetype_manual(
    values = c(1,1),guide = guide_legend(override.aes = list(colour = c("blue","red")))
  ) + 
  scale_colour_continuous(guide = FALSE) +
  theme(legend.justification = c(1,legend.position = c(1,1))

并获得以下图表:

enter image description here

编辑

我刚刚意识到,该解决方案没有保留颜色schme(绿点)。另一种解决方案是在show.legend = FALSE中使用geom_point。 因此,如果您这样做:

ggplot(df,color = C.I),show.legend = FALSE) + 
  scale_colour_gradientn(colours=c("green","red")))
  )  +
  theme(legend.justification = c(1,1))

您将获得以下情节:

enter image description here

本文链接:https://www.f2er.com/3088012.html

大家都在问