Skip to content

Instantly share code, notes, and snippets.

@sdtaylor
Last active October 20, 2022 15:53
Show Gist options
  • Save sdtaylor/4f92f0e620aada78ae4c07472d20d973 to your computer and use it in GitHub Desktop.
Save sdtaylor/4f92f0e620aada78ae4c07472d20d973 to your computer and use it in GitHub Desktop.
ggplot varying length tickmarks
library(tidyverse)
#------------------------------------
# Have x-axis labels offset slightly for clarity using guide_axis(n.dodge = 2),
# but also have different length tickmarks to make it look nicer.
# See https://twitter.com/ecologyofgavin/status/1344102509585997824
# Derived from https://stackoverflow.com/a/51312611/6615512
# Requires ggplot 3.0.0 or greater
#------------------------------------
# Some data to plot
lizards = tribble(
~group, ~n,
'Ag', 5,
'0-3', 8,
'8-10', 7.5,
'12-15',8,
'20-32',7.8,
'Natural',8.1
)
# put groups in order defined above
lizards$group = forcats::fct_inorder(lizards$group)
# Tick mark lengths adjusted here
top_y_pos = 2
bot_y_pos = 0.8
custom_ticks = tribble(
~group, ~y_end,
'Ag', top_y_pos,
'0-3', bot_y_pos,
'8-10', top_y_pos,
'12-15', bot_y_pos,
'20-32', top_y_pos,
'Natural',bot_y_pos
)
ggplot(lizards, aes(x=group,y=n)) +
geom_point(aes(color=group),size=8) +
scale_color_viridis_d() +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
geom_linerange(data = custom_ticks, aes(x=group, ymax=2.7, ymin=y_end), # The custom tickmarks
size=2,
inherit.aes = F) +
theme_bw(50) +
coord_cartesian(clip='off', ylim=c(3,10)) + # clip off allow geoms, here the tickmarks, to be drawn outside the plots
theme(legend.position = 'none',
axis.title = element_blank(),
panel.border = element_rect(color='black'), # make the border and y ticks match the custom ticks
axis.ticks.y = element_line(color='black'),
axis.ticks.x = element_blank()) # turn offf the regular tickmarks
@sdtaylor
Copy link
Author

sdtaylor commented Jan 1, 2021

Creates the following

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment