ggplot2:添加带有标签的第二个x轴 [英] ggplot2: Adding a second x-Axis with labels

查看:67
本文介绍了ggplot2:添加带有标签的第二个x轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似的东西.就我而言,我在x轴上确实有6个不同的标签-分别是一月",二月",六月",七月"和九月",十月".如您所见,两个月总是可以分为一个季节:冬季",夏季"和秋天".我有六个值(每个月一个),让它成为温度.现在,我的x轴有6个刻度和标签.但是,我想添加第二个轴,在一月"和二月"下方出现冬季",依此类推.关于如何工作的任何想法吗?

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

非常感谢!

推荐答案

这是在主图和轴标签下方添加文本的一种非常巧妙的方法.由于我没有原始数据,因此让我来说明如何使用"mtcars"数据:

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)

您可以将ymin和xmin值调整为星期,以移动文本.

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

如果要将 gg_table 另存为grob,则需要使用 arrangeGrob()和克隆ggsave并绕过类检查"(根据类似问题的答案):

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)

这篇关于ggplot2:添加带有标签的第二个x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆