[英]ggplot2: Adding a second x-Axis with labels
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". 就我而言,我在x轴上确实有6个不同的标签-分别是“一月”,“二月”,“六月”,“七月”和“九月”,“十月”。 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. 现在,我的x轴有6个刻度和标签。 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! 非常感谢!
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: 由于我没有原始数据,因此让我说明如何使用“ mtcars”数据:
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. 您可以tweek ymin和xmin值来移动文本。
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 ): 如果要将gg_table
保存为gg_table
,则需要使用arrangeGrob()
和“克隆ggsave并绕过类检查”(根据类似问题的答案 ):
g <- arrangeGrob(gg_table)
ggsave <- ggplot2::ggsave
body(ggsave) <- body(ggplot2::ggsave)[-2]
ggsave(file="./figs/figure.png", g)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.