I'd like plots that share a horizontal axis, but with different vertical axes. This would be easy using facet_grid
if I wanted them to use the same geom
, but they have different geoms.
The best I have so far to above facet_grid
a bit:
library(gridExtra)
library(reshape2)
n = 10
df <- data.frame(X = seq.int(n),
Count = sample(1:50, size=n),
Y = sample(1:10000000, size=n))
long <- melt(df, id="X")
long$Y <- with(long, ifelse(variable=="Y", value, NA))
long$Count <- with(long, ifelse(variable=="Count", value, NA))
long$variable <- factor(long$variable, levels = c("Y", "Count"))
ggplot(long) +
geom_point(aes(x=X, y=Y)) +
geom_bar(aes(x=X,y=Count), stat="identity") +
facet_grid(variable ~ ., scales="free_y") +
ylab("")
Prior to that, I was doing this (which can get the axis alignment wrong and is in general very fragile):
pointsPlot <- ggplot(df) + geom_point(aes(x=X, y=Y))
barPlot <- ggplot(df) + geom_bar(aes(x=X, y=Count), stat="identity")
grid.arrange(pointsPlot, barPlot, ncol=1)
Does anyone have less hacky way to suggest?