ggplot折线图中的多行x轴标签 [英] Multi-row x-axis labels in ggplot line chart

查看:330
本文介绍了ggplot折线图中的多行x轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:此问题已标记为重复,但回复






另请参阅@ eipi10的精彩回答:预防随着时间序列不必要地多次显示一年


Edit: This question has been marked as duplicated, but the responses here have been tried and did not work because the case in question is a line chart, not a bar chart. Applying those methods produces a chart with 5 lines, 1 for each year - not useful. Did anyone who voted to mark as duplicate actually try those approaches on the sample dataset supplied with this question? If so please post as an answer.

Original Question:

There's a feature in Excel pivot charts which allows multilevel categorical axes.I'm trying to find a way to do the same thing with ggplot (or any other plotting package in R).

Consider the following dataset:

set.seed(1)
df=data.frame(year=rep(2009:2013,each=4),
              quarter=rep(c("Q1","Q2","Q3","Q4"),5),
              sales=40:59+rnorm(20,sd=5))

If this is imported to an Excel pivot table, it is straightforward to create the following chart:

Note how the x-axis has two levels, one for quarter and one for the grouping variable, year. Are multilevel axes possible with ggplot?

NB: There is a hack with facets that produces something similar, but this is not what I'm looking for.

library(ggplot2)
ggplot(df) +
  geom_line(aes(x=quarter,y=sales,group=year))+
  facet_grid(.~year,scales="free")

解决方案

We use arguments in theme to remove the default x axis text (axis.title.x/ axis.text.x = element_blank()) and extra margins are added (plot.margin).

New labels are added using annotate(geom = "text",. By converting plot object to a grob (ggplot_gtable(ggplot_build(), clipping of x axis labels can be turned off.

library(ggplot2)
g1 <- ggplot(data = df, aes(x = interaction(year, quarter, lex.order = TRUE), 
                            y = sales, group = 1)) +
  geom_line(colour = "blue") +
  coord_cartesian(ylim = c(35, 65), expand = FALSE) +
  annotate(geom = "text", x = seq_len(nrow(df)), y = 34, label = df$quarter, size = 4) +
  annotate(geom = "text", x = 2.5 + 4 * (0:4), y = 32, label = unique(df$year), size = 6) +
  theme_bw() +
  theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank())


# remove clipping of x axis labels
g2 <- ggplot_gtable(ggplot_build(g1))
g2$layout$clip[g2$layout$name == "panel"] <- "off"
grid::grid.draw(g2)


See also the nice answer by @eipi10 here: Prevent showing the year several times unnecessarily with time series

这篇关于ggplot折线图中的多行x轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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