Mariano Avino
Mariano Avino

Reputation: 75

Generate two plots with same x axis breaks

I have two plots I want the x axes being broken by the same way. This is the code for plot 1:

m <- read.csv('Finalfor1lowergreaterthan1.csv', header=T, row.names=1)
m <- m[m$SVM.Count >= 40,]
boxOdds = m$Odd

df <- data.frame(
  yAxis = length(boxOdds):1,
  boxnucleotide = m$Position,
  boxCILow = m$lower,
  boxCIHigh = m$upper,
  Mutation = m$Resistance)

ticksy <- c(seq(0,0.3,by=.1), seq(0, 1, by =.5), seq(0, 20, by =5), seq(0, 150, by =50))
ticksx <- c(seq(0,300,by=25))
p <- ggplot(df, 
            aes(x = boxnucleotide, y = boxOdds, colour=Mutation, label=rownames(m)))
p1 <- p + 
  geom_errorbar(aes(ymax = boxCIHigh, ymin = boxCILow), size = .5, height = .01) +
  geom_point(size = 1) +
  theme_bw() +
  theme(panel.grid.minor = element_blank()) +
  scale_y_continuous(breaks=ticksy, labels = ticksy) +
  scale_x_continuous(breaks=ticksx, labels = ticksx) +
  coord_trans(y = "log10") +
  ylab("Odds ratio (log scale)") +
  scale_color_manual(values=c("#00BFC4","#F8766D","#619CFF")) +
  xlab("Integrase nucleotide position") + 
  geom_text(size=2,hjust=0, vjust=0)

plot1

Then I have another plot:

m <- read.csv('Finalfor20lowergreaterthan1.csv', header=T, row.names=1)
#m <- m[m$SVM.Count >= 40, ]
boxOdds = m$Odd

df <- data.frame(
  yAxis = length(boxOdds):1,
  boxnucleotide = m$Position,
  boxCILow = m$lower,
  boxCIHigh = m$upper,
  Mutation = m$Resistance)

ticksy <- c(seq(0,0.3,by=.1), seq(0, 1, by =.5), seq(0, 20, by =5), seq(0, 150, by =50))
ticksx <- c(seq(0,300,by=25))
p <- ggplot(df, 
            aes(x = boxnucleotide, y = boxOdds, colour=Mutation, label=rownames(m)))
p1 <- p + 
  geom_errorbar(aes(ymax = boxCIHigh, ymin = boxCILow), size = .5, height = .01) +
  geom_point(size = 1) +
  theme_bw() +
  theme(panel.grid.minor = element_blank()) +
  scale_y_continuous(breaks=ticksy, labels = ticksy) +
  scale_x_continuous(breaks=ticksx, labels = ticksx) +
  coord_trans(y = "log10") +
  ylab("Odds ratio (log scale)") +
  scale_color_manual(values=c("#00BFC4","#F8766D","#619CFF")) +
  xlab("Integrase nucleotide position") + 
  geom_text(size=2,hjust=0, vjust=0)

plot2

Why is plot 1 starting from 75 on x axis and plot 2 starting at 100...how can plot2 start at 75 as well and being scaled like plot 1.

The two codes get the same piece of: ticksx <- c(seq(0, 300, by=25))

Upvotes: 1

Views: 221

Answers (1)

asachet
asachet

Reputation: 6921

A good technique to align the axis range on different plots is to use expand_limits.

You can simply use p1 + expand_limits(x=c(0, 300)). This will ensure the x-axis contains at least 0 and 300 on all your plots. You can also control the y-axis range by using the y argument.

From ?expand_limits:

Sometimes you may want to ensure limits include a single value, for all panels or all plots. This function is a thin wrapper around geom_blank() that makes it easy to add such values.

Upvotes: 1

Related Questions