Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active May 5, 2023 09:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt-dray/f150fa332cce4c509d5a85577e6d8fbf to your computer and use it in GitHub Desktop.
Save matt-dray/f150fa332cce4c509d5a85577e6d8fbf to your computer and use it in GitHub Desktop.
Can you move tickmarks between bars on the categorical x-axis of a {ggplot2} barplot?
# From the Analysis Function's guidance on charts: 'When an axis shows
# categorical data, you do not necessarily need tick marks, but if you do use
# them labels should be aligned between them.' Is this actually possible in
# ggplot2? A quick example.
#
# Link to guidance:
# https://analysisfunction.civilservice.gov.uk/policy-store/data-visualisation-charts/#section-3:~:text=on%20the%20chart.-,Tick%20marks,-Tick%20marks%20are
library(ggplot2)
fruit_df <- data.frame(fruit = sample(c("apples", "oranges"), 100, TRUE))
ggplot(fruit_df) +
geom_bar(aes(fruit)) +
theme(
axis.ticks.x = element_blank(), # delete ticks
axis.line.y = element_line() # add y axis line
) +
coord_cartesian(clip = "off", ylim = c(3, 65)) + # zoom y axis to extent
geom_hline(yintercept = 0) + # add fake x axis
annotate( # add fake ticks
"segment",
x = c(0.5, 1.5, 2.5),
xend = c(0.5, 1.5, 2.5),
y = 0,
yend = -1.5
)
# For comparison, a simple sketch with base plot
barplot(table(fruit_df), xlim = c(0.1, 2.5))
axis(side = 1, at = c(0.1, 1.3, 2.5), labels = NA)
@matt-dray
Copy link
Author

Output of {ggplot2} code:
ggplot2-bar-discrete-ticks
Output of the base R code:
base-bar-discrete-ticks

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