QPaps
QPaps

Reputation: 312

Label every n-th x-axis tick on boxplot

I would like to remove every n-th x-axis tick labels from a geom_boxplot (ggplot).

For example take this dummy dataframe:

Lat <- c(rep(50.70,3), rep(51.82,3), rep(52.78,3), rep(56.51,3))
y <- c(seq(1,2, by=0.5), seq(1,3, by=1), seq(2,6,by=2), seq(1,5,by=2))
df <- as.data.frame(cbind(Lat, y))

I can make a ggplot boxplot like so:

box_plot <- ggplot(df, aes(x=as.factor(Lat), y=y))+
  geom_boxplot()+
  labs(x="Latitude")+
  scale_y_continuous(breaks = pretty_breaks(n=6)) +
  theme_classic()
box_plot

However I would like to remove the labels from the middle two boxes.

I know I can achieve this by changing the labels to simply be blank (as below). However, my real dataframe has many more than 4 ticks so this would be time consuming never mind more likely for human error!

box_plot2 <- ggplot(df, aes(x=as.factor(Lat), y=y))+
  geom_boxplot()+
  labs(x="Latitude")+
  scale_y_continuous(breaks = pretty_breaks(n=6)) +
  scale_x_discrete(labels=c("50.70", " ", " ", "56.51"))+
  theme_classic()
box_plot2

Is there a way to produce the above plot without having to manually set the labels?

For example label every n-th tick on the x axis?

Thanks in advance!

Upvotes: 0

Views: 1147

Answers (1)

stefan
stefan

Reputation: 124268

This can be achieved like. As an example I just plot "every" third tick. Basic idea is to add an index for the factor levels. This index can then be used to specify the breaks or ticks one wants to plot. Try this:

Lat <- c(rep(50.70,3), rep(51.82,3), rep(52.78,3), rep(56.51,3))
y <- c(seq(1,2, by=0.5), seq(1,3, by=1), seq(2,6,by=2), seq(1,5,by=2))
df <- as.data.frame(cbind(Lat, y))

library(ggplot2)
library(scales)
library(dplyr)

df <- df %>% 
  mutate(Lat1 = as.factor(Lat),
         Lat1_index = as.integer(Lat1))

# Which ticks should be shown on x-axis
breaks <- df %>% 
  # e.g. plot only every third tick
  mutate(ticks_to_plot = Lat1_index %% 3 == 0) %>% 
  filter(ticks_to_plot) %>% 
  pull(Lat1)

box_plot2 <- ggplot(df, aes(x=Lat1, y=y))+
  geom_boxplot()+
  labs(x="Latitude")+
  scale_y_continuous(breaks = pretty_breaks(n=6)) +
  scale_x_discrete(breaks = breaks)+
  theme_classic()
box_plot2

Created on 2020-03-30 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions