2013-12-13 44 views
30

編輯:此問題已被標記爲重複,但已回覆here已被嘗試並且無法正常工作,因爲所討論的情況是折線圖而非酒吧圖表。應用這些方法會生成一個包含5行的圖表,每年1個 - 無用。是否有人投票標記爲重複,實際上是在這個問題提供的樣本數據集上嘗試這些方法?如果是這樣,請發帖作爲答案。ggplot折線圖中的多行x軸標籤

原題:

有在Excel數據透視圖一個功能,它允許多級分類axes.I'm試圖找到一種方式做同樣的事情ggplot(或R中的任何其他繪圖軟件包) 。

考慮以下數據集:

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)) 

如果這被導入到Excel透視表,它是簡單的創建以下圖表:

注意如何x軸有兩個級別,分別爲一個季度和一個分組變量,一年。 ggplot是否可以使用多級軸?

注意:有一個方面可以產生類似的方面,但這不是我正在尋找的。

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

回答

39

我們用論據theme刪除默認的x軸的文字(axis.title.x/axis.text.x = element_blank())和額外的利潤相加(plot.margin)。

使用annotate(geom = "text",添加新標籤。通過將繪圖對象轉換爲grob(ggplot_gtable(ggplot_build(),可以關閉x軸標籤的裁剪。

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) 

enter image description here


也是不錯的答案見@ eipi10這裏:Prevent showing the year several times unnecessarily with time series

+0

非常好!另外,使用'x = interaction(year,quarter)'對我來說是新的。 – jlhoward

20

亨裏克·建議的代碼做的工作,對我幫助很大!我認爲解決方案具有很高的價值。但請注意,代碼的第一行中存在一個小錯誤,導致錯誤的數據順序。取而代之的

... aes(x = interaction(year,quarter), ... 

應該

... aes(x = interaction(quarter,year), ... 

得到的圖形具有正確的順序中的數據。

enter image description here

P.S.我提出了一個編輯(到目前爲止被拒絕),由於缺乏聲譽,我不能評論,我寧願做。