lin hoober
lin hoober

Reputation: 51

closing the gap between two graphs with patchwork

I want to close the gap between the two graphs and to make it seem like it is a single graph.

I saw [this solution][1] but it's doesn't work for me.

Thanks in advance

![My plot][2]

library(ggplot2)
library(patchwork)


bp_data=read.csv("./LA metals.csv")
values<- read.csv("metals values.csv")
b = seq(from = 0, to = 226, by = 10)
l = c(0, 226)

year=bp_data$Name=as.factor(bp_data$Name)
bp=ggplot(bp_data,aes(x = Name, y = Pb.Ca)) +
  stat_boxplot(geom ='errorbar',width=0.5)+
  stat_summary(fun=mean, geom="point", shape=20, size=3, color="cornflowerblue")+
  geom_boxplot(color = "black", width = 0.5)+
  geom_hline(yintercept = 5.4, size=1,color="red")+
  scale_y_continuous(breaks = b, limits = l,expand = c(0, 0))



Pb.lach=subset(values[c(3:4),c(1,6:7)])
Name=Pb.lach$Term=as.factor(Pb.lach$Term)
val=ggplot(Pb.lach,aes(x = Name, y = Pb.Ca))+
  geom_point()+
  geom_errorbar(aes(ymin=Pb.Ca-SD.2, ymax=Pb.Ca+SD.2), width=.2)+
  scale_y_continuous(breaks = b, limits = l,expand = c(0, 0))
 

bp+val

Upvotes: 5

Views: 2903

Answers (1)

stefan
stefan

Reputation: 124413

One option to remove the gap between plots when using patchwork:

  1. Remove the plot.margins from both plots.
  2. For the second plot remove all y axis elements an set the tick length to zero.

Using mtcars as example data:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars, aes(factor(cyl), hp)) +
  geom_boxplot() +
  theme(plot.margin = margin(0, 0, 0, 0, "pt"))

p2 <- ggplot(mtcars, aes(factor(cyl), hp)) +
  geom_point() +
  theme(plot.margin = margin(0, 0, 0, 0, "pt"),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        axis.line.y = element_blank(),
        axis.title.y = element_blank(),
        axis.ticks.length.y = unit(0, "pt"))

p1 + p2

Upvotes: 5

Related Questions