0

I am looking for something similar. In my case, I do have 6 different labels on the x axis - let it be "January", "February", "June", "July" and "September", "October". As you can see, 2 months can always be grouped into one season: "Winter", "Summer" and "Autumn". I have six values (one for each month), let it be temperature. Now my x-Axis has 6 ticks and labels. I would, however, like to add a second axis with "Winter" appearing below "January" and "February" and so on. Any idea on how that could work?

Here's my code so far:

p1 <- ggplot(df, aes(colour=group, y= temperature, x= month))
p1 <- p1 + geom_point(aes(shape=c("15", "15", "16", "16", "17", "17")),size = 1.5)+               
  geom_errorbar(limits2, width=0.1, size = 0.5) +                                        
  scale_y_continuous(limits=c(0,5), name = "Temperature")+                                
  theme(axis.title.y = element_text(vjust=0.4))+                                          
  scale_x_discrete(name = "MONTH", labels=c("January", "February", "June", "July", "September", "October"))+
  theme(axis.title.x = element_text(vjust=-0.2))
p1

Thanks so much!

1 Answer 1

1

Here is very an inelegant way to add texts below the main plot and the axis label. Since I don't have the original data, let me illustrate using the "mtcars" data:

library(ggplot2)
library(gridExtra)
(g0 <- ggplot(mtcars, aes(gear, mpg, colour=factor(am))) + geom_point(size=4) +
   theme(plot.margin = unit(c(1,1,3,1), "cm")))

Text1 <- textGrob("Spring")
Text2 <- textGrob("Summer")
Text3 <- textGrob("Fall")
(g1 <- g0 + annotation_custom(grob = Text1,  xmin = 3, xmax = 3, ymin = 5, ymax = 5) +
   annotation_custom(grob = Text2,  xmin = 4, xmax = 4, ymin = 5, ymax = 5) +
   annotation_custom(grob = Text3,  xmin = 5, xmax = 5, ymin = 5, ymax = 5))

gg_table <- ggplot_gtable(ggplot_build(g1))
gg_table$layout$clip[gg_table$layout$name=="panel"] <- "off"
grid.draw(gg_table)

You can tweek the ymin and xmin values to move the texts around.

If you want to save the gg_table as a grob, you need to use arrangeGrob() and "clone ggsave and bypass the class check" (according to the answer to a similar question):

g <- arrangeGrob(gg_table)
ggsave <- ggplot2::ggsave
body(ggsave) <- body(ggplot2::ggsave)[-2]
ggsave(file="./figs/figure.png", g)

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much, that works perfectly! It is just that my ggsave function now does not combine the plot and the table...any idea on how to solve this?
For some reason, you need to use arrangeGrob() to assign the gg_table to a grob. See above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.