I am outputting a lot of figures in a loop where the y axis varies in scale and range. I noticed that in most instances the last tick is well before the end of the axis and the data often extends above this last tick. I'd like a programmatic way to tell ggplot to put a tick at the end of the axis or at least to the highest data point plotted so the full range of data is annotated.
here is some data that illustrates this problem on both the x and y axis:
library(ggplot2)
count<- c(1, 2, 3, 8, 4, 6, 2, 2, 4, 6, 8, 13)
position<-c(1, 2, 3, 4, 5, 6, 7, 2, 4, 6, 8, 13)
group<- c('a', 'a', 'a', 'a', 'a', 'a', 'a', 'b','b', 'b', 'b','b')
data<-data.frame(count, position, group)
plot1<- ggplot(data, aes(x=position, y=count, color=group))
geom_line(size=2)
theme(
panel.background = element_rect(fill="white"),
axis.line = element_line(size=1, colour = "black"),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, face="bold", size=12, color="black"),
axis.text.y = element_text(face="bold", size=12, color="black"),
legend.position = "bottom"
)
This is what the image currently looks like:
When I output this in a loop using tiff() and dev.off() with a defined size, a lot of the axis ticks look like this. Any thoughts on how to fix this?
CodePudding user response:
You can specify where breaks appear with the scale_*_continuous
functions. You can supply a sequence defined by the min and max of each axis:
plot1<- ggplot(data, aes(x=position, y=count, color=group))
geom_line(size=2)
scale_y_continuous(breaks = seq(min(data$count), max(data$count), length = 5))
scale_x_continuous(breaks = seq(min(data$position), max(data$position), length = 5))
theme(
panel.background = element_rect(fill="white"),
axis.line = element_line(size=1, colour = "black"),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, face="bold", size=12, color="black"),
axis.text.y = element_text(face="bold", size=12, color="black"),
legend.position = "bottom"
)
print(plot1)