如何消除ggplot图例中的空白?

Ran*_*cho 2 r ggplot2

有我的数据框

Days,Observed,Simulated
0,0,424.8933328
1,1070,1116.781453
2,2360,2278.166227
3,3882,3854.781359
4,5712,5682.090936
5,7508,7565.230044
6,9126,9343.991798
7,10600,10919.17995
8,11893,12249.07067
9,13047,13332.93044
10,14022,14193.53941
11,14852,14863.84784
12,15480,15378.56415
13,16042,15769.6773
14,16362,16064.57556
15,16582,16285.66038
16,16766,16450.70955
17,16854,16573.54275
18,16854,16664.74816
Run Code Online (Sandbox Code Playgroud)

这是我的代码,希望我没有错过一些信息

dt <- read.csv('data.csv')
days <- dt$Days
Observed <- dt$Observed
Simulated <- dt$Simulated

require(ggplot2)
R <- ggplot(dt, aes(x = days))+geom_line(y=Simulated, color="red", size=0.5)+
  geom_point(y=Observed, color="midnightblue", size=1.75)
a <- geom_line(aes(y = Simulated, col='Simulated'))
n <- geom_point(aes(y = Observed, fill = "Observed"), col='blue')
c <- ggtitle("2.5kg of Placenta & 0.5kg of seed") 
h <- labs(x = 'Time(Days)', y = "Cumulative Biogas Yield(ml)", 
          colour = NULL, fill = "Legend")
o <- theme(plot.title = element_text(hjust = 0.1))+
  theme( plot.title = element_text(colour = "midnightblue"),
         axis.title.x = element_text(colour = "black", size = 14),
         axis.title.y = element_text(colour = "black", size = 14),
         legend.title = element_text(colour = "black", size = 14),
         legend.text = element_text(colour = "black", size = 12.5),
         axis.text.x = element_text(colour = "black", size = 14),
         axis.text.y = element_text(colour = "black", size = 14))
d <- scale_color_manual(values = 'red')
s <- scale_fill_manual(values = 'midnightblue')
Myplot <- R+a+n+c+h+o+d+s
Myplot
Run Code Online (Sandbox Code Playgroud)

我得到的结果在变量之间有很大的差距,需要删除

传说中的变量之间有很大的差距

我想要的是如下:

变量之间没有间隙

我已经编辑了画家上的图表以获得我想要的东西,但它的工作令人厌烦,我希望拥有可以简化我的过程的代码。提前致谢。

che*_*123 5

您可以使用两个主题元素的组合来调整两个图例之间的间距:legend.spacinglegend.margin。我玩了一下这些,这种组合似乎效果很好:

Myplot + theme(
    legend.spacing = unit(0,'pt'),
    legend.margin = margin(t=0,b=0,unit='pt')
  )
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 旁注 另外,只是想注意,当您想将两个图例压缩在一起,但有一个标题时,最好像您一样这样做(其中一个图例标题设置为NULL而不是空字符""NULL有效地删除图例标题为元素,使间距变得更容易,而""仍然带有标题的间距,即使没有什么表示。如果更换NULL""在你的代码,你会看到这与:) ......这么好的工作。