Reputation: 6314
I have 2 data sets I'd like to ggplot
side by side so they share the y-axis
.
I thought of using ggplot
's facet_wrap
for this but ned to find out how to stitch
them together. This is what I have so far:
df.1 <- data.frame(x=c(-0.678071905112638,1.32192809488736,-0.678071905112638,1.32192809488736,-0.678071905112638,1.32192809488736),
y=c(62.8805462356349,73.027603062927,88.4090942806369,87.6879626013305,55.9895740872068,93.5396099910227),
side=1,stringsAsFactors = F)
df.2 <- data.frame(x=c(1.32192809488736,3.32192809488736,1.32192809488736,1.32192809488736),
y=c(73.027603062927,7.33717302418609,87.6879626013305,93.5396099910227),
side=2,stringsAsFactors = F)
df <- rbind(df.1,df.2)
df$side <- factor(df$side,levels=c(1,2))
require(ggplot2)
ggplot(df,aes(x=x,y=y))+geom_point()+facet_wrap(~side,ncol=2,scales="free")+stat_smooth(method="lm",formula=y~x,colour="black")+theme(strip.text.y=element_text())
How do I get rid of the y-axis of the right facet and remove the space between the facets so they appear as a single figure? Also, they need to have the same y-axis coordinates.
To be clear, the reason I'm using two facets
is because I'm fitting an lm to each df
separately.
Upvotes: 0
Views: 175
Reputation: 93871
You could adjust the margin between the facets to remove the space. Also, use scales="free_x"
so that only the x-axis scales will be free, while the y-axis scales will be the same. Because the y-axis scales are the same in each facet, the scale won't be repeated on the right facet:
theme_set(cowplot::theme_cowplot())
ggplot(df,aes(x=x,y=y))+geom_point() +
facet_wrap(~side, ncol=2, scales="free_x") +
stat_smooth(method="lm", formula=y~x, colour="black") +
theme(panel.spacing = unit(-1.25, "lines"))
But you could also avoid facetting and get separate lines using a color aesthetic. This approach puts everything on a single panel, so you don't have to worry about lining up the x-scales between facets:
ggplot(df,aes(x=x, y=y)) +
geom_point() +
stat_smooth(method="lm",formula=y~x, aes(colour=side))
Upvotes: 1
Reputation: 23231
Set the y limits with ylim
. Adjust the gap with panel.spacing.x
. Remove the unwanted labels with axis.text.y
and the tick marks with axis.ticks
.
ggplot(df,aes(x=x,y=y))+geom_point()+ ylim(0, 120) +
facet_wrap(~side,ncol=2,scales="free")+
stat_smooth(method="lm",formula=y~x,colour="black")+
theme(strip.text.y=element_text(), axis.text.y = element_blank(),
axis.ticks = element_blank(), panel.spacing.x=unit(0, "lines"))
Upvotes: 1