tassones
tassones

Reputation: 1692

How can I add custom ticks and text to ggplot2 x-axis

I am trying to add custom ticks to a geom_col figure but have not been able to figure it out. I would like for the x-axis to display both the individual siteID and below that the grouping Region ID (multiple sites can belong to one region). Below is a reprex example of what I'm trying to do (please no annoying comments like "YoU sHoUlDn'T uSe GeOm_CoL tO dIsPlAy MeAnS").

Example below is as far as I have gotten:

library(data.table)
library(dplyr)

df1 <- data.frame(matrix(ncol = 3, nrow = 18))
x <- c("siteID", "Region", "Wtemp")
colnames(df1) <- x
df1$siteID <- c("ace","ace","ace",
                "hud","hud","hud","hud",
                "apa","apa","apa","apa","apa",
                "cbv","cbv","cbv","cbv","cbv","cbv")
df1$Region <- c("North","North","North",
                "North","North","North","North",
                "South","South","South","South","South",
                "East","East","East","East","East","East")
set.seed(55)
df1$Wtemp <- rnorm(18,20,10)

test_table <- df1 %>%
  group_by(siteID, Region) %>%
  summarise(MeanWtemp = mean(Wtemp))

test_table %>%
  arrange(-desc(Region)) %>%
  mutate(siteID = factor(siteID, levels = c("cbv","ace","hud","apa"))) %>%
  ggplot(aes(x = siteID, y = MeanWtemp)) +
  geom_col(color = "black") + 
  labs(x = "Site & Region",
       y = "Mean Water Temp. (C)") +
  theme_bw() +
  theme(plot.margin = margin(5,5,50,5,"pt"),,
        panel.grid = element_blank(),
        text = element_text(size = 14),
        axis.text.x = element_text(size = 14, color = "black"),
        axis.text.y = element_text(size = 14, color = "black"),
        axis.title.x = element_text(vjust = -15))

The figure should look something like this picture below where the x-axis has custom ticks at certain positions and of certain lengths along with custom text specifying Region.

enter image description here

Upvotes: 1

Views: 979

Answers (1)

Jon Spring
Jon Spring

Reputation: 66425

I don't think there's a built-in way to do this, but you can fake it thusly. clip = "off" in coord_cartesian lets us plot outside the plot range, and specifying ylim makes it so the y axis is not expanded to accommodate the annotations within their range. The annotation positions are customized to this data, but with some planning you could probably come up with a procedure to generate it automatically.

  #...your code
  coord_cartesian(clip = "off", ylim = c(0, NA)) +
  annotate("text", x = c(1, 2.5, 4), y = -4, label = c("East", "North", "South"), size = 5) + 
  annotate("segment", x = c(1.5, 3.5), xend = c(1.5, 3.5), y = -1, yend = -5) +
  #... the rest of your code

enter image description here

Upvotes: 2

Related Questions