Jon Jon -4 years ago 132
R Question

ggplot2: How to end y-axis on a tick mark?

I am making several different plots with different axis ranges, so this question does not apply to only the code I am showing here. I tried modifying the breaks and intervals of tick marks, but for some plots the y-axis always continues after the last break. But for some it just works out fine like this.

Here is my current plot, and the code. I would like to end the y-axis with a tick mark on 60:

enter image description here

# Set nucleotide sequence for x-axis labels
my_labs = c("C", "T", "A", "C", "A", "T", "A", "A", "A", "T", "A", "C", "A", "C", "A", "T", "G", "T", "C", "T", "C", "T", "G", "C", "T", "C", "G", "T", "T", "C", "G", "G", "G", "G", "G", "C", "C", "G", "G", "T", "A", "T", "G", "C", "T", "A", "C", "A", "C", "G", "G", "A", "A", "C", "G", "T", "G", "A", "G", "A", "G", "A", "C", "C", "C", "C", "T", "C", "G", "G", "A", "A", "C", "T", "G", "G", "C", "A", "T", "A", "G", "A", "C", "T", "T", "G", "T", "G", "T", "A", "T", "A", "A", "A", "A", "G", "A", "A", "T")

# Set color of each nucleotide
my_cols = c("Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Blue", "Black", "Black", "Black", "Black", "Black", "Black", "Black", "Black")

ggplot(data = miRNA2) +
geom_line(mapping = aes(x = Position, y = CPM), colour="red") +
scale_y_continuous(breaks = seq(0, 60, 10)) +
ylab("Counts per million") +
scale_x_continuous(breaks=1:99, labels=my_labs, expand = c(0, 0)) +
theme(axis.text.x = element_text(color = my_cols, family = "Courier", size = 6),
panel.grid.minor.x=element_blank(), panel.grid.major.x=element_blank(), panel.grid.minor.y=element_blank(), panel.background = element_blank(),
axis.line = element_line(colour = "black")) +
xlab("Supercontig_1.420:40270-40368") +
ggtitle("Sar-Mir-Nov-2") +
theme(plot.title = element_text(hjust = 0.5))

Answer Source

just add limits = c(0,60) and expand = c(0,0) to your scale_y_continuous:

scale_y_continuous(breaks = seq(0, 60, 10), limits = c(0,60), expand = c(0,0))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download