Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding minor tick marks to the x axis in ggplot2 (with no labels)

Tags:

r

ggplot2

Below is example code of a plot that does almost exactly what I want. The only thing I want to add is tick marks on the x axis (same size as the major ticks) according to the minor_breaks defined below.

df <- data.frame(x = c(1900,1950,2000), y = c(50,75,60))      p <- ggplot(df, aes(x=x, y=y)) p + geom_line() +    scale_x_continuous(minor_breaks = seq(1900,2000,by=10),                      breaks = seq(1900,2000,by=50),                      limits = c(1900,2000),                      expand = c(0,0)) +   scale_y_continuous(breaks = c(20,40,60,80),                      limits = c(0,100)) +   theme(legend.position="none",         panel.background = element_blank(),          axis.line = element_line(color='black'),         panel.grid.minor = element_blank()) 
like image 261
JimmyT Avatar asked Jan 23 '13 21:01

JimmyT


People also ask

How do I add a minor tick mark in ggplot2?

To adjust the number of minor ticks, you just change the number of minor breaks using the minor_breaks argument of the continuous scale functions. The vector you give the minor_breaks argument will define the position of each minor tick.

How do I add a tick mark to the X axis?

To create a plot with tick marks manually between X-axis values in base R, we first need to create the plot without X-axis labels then add the axis values using axis function with appropriate labels, this will create tick marks as well as labels.

How do I add a tick to a graph in R?

The following steps can be used : Hide x and y axis. Add tick marks using the axis() R function. Add tick mark labels using the text() function.


1 Answers

This would do it in the precise instance:

scale_x_continuous(breaks= seq(1900,2000,by=10),                    labels = c(1900, rep("",4), 1950, rep("",4), 2000),                    limits = c(1900,2000), expand = c(0,0)) + 

Here's a function that is not bullet-proof but works to insert blank labels when the beginning and ending major labels are aligned with the start and stopping values for the at argument:

insert_minor <- function(major_labs, n_minor) {labs <-                                c( sapply( major_labs, function(x) c(x, rep("", 4) ) ) )                               labs[1:(length(labs)-n_minor)]} 

Test:

p <- ggplot(df, aes(x=x, y=y))   p + geom_line() +    scale_x_continuous(breaks= seq(1900,2000,by=10),                       labels = insert_minor( seq(1900, 2000, by=50), 4 ),                       limits = c(1900,2000), expand = c(0,0)) +   scale_y_continuous(breaks = c(20,40,60,80), limits = c(0,100)) +   theme(legend.position="none", panel.background = element_blank(),          axis.line = element_line(color='black'), panel.grid.minor = element_blank()) 
like image 161
IRTFM Avatar answered Oct 16 '22 21:10

IRTFM