编辑:这个问题已被标记为复制,但反应在这里都试过了,没有工作,因为有问题的情况是折线图,而不是一个柱状图。 应用这些方法产生具有5行,1每年为图表 - 没有用处。 没有人谁投标记为重复的实际尝试与这个问题提供的样本数据集的那些方法? 如果是的话,请张贴作为一个答案。
原题:
有一个在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")
新的标签使用添加annotate(geom = "text",
关掉x轴标签用的限幅clip = "off"
中coord_cartesian
。
使用theme
添加额外的利润( plot.margin
)和删除( element_blank()
)x轴文本( axis.title.x
, axis.text.x
)和垂直网格线( panel.grid.x
)。
library(ggplot2)
ggplot(data = df, aes(x = interaction(year, quarter, lex.order = TRUE),
y = sales, group = 1)) +
geom_line(colour = "blue") +
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) +
coord_cartesian(ylim = c(35, 65), expand = FALSE, clip = "off") +
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())
另见@ eipi10这里漂亮的答案: 两行嵌套变量x轴标签(低于去年月)
亨利克建议的代码不工作,对我帮助很大! 我认为解决方案具有很高的价值。 但是,请注意,有代码的第一行,这会导致数据错误的顺序一个小misstake。 代替
... aes(x = interaction(year,quarter), ...
它应该是
... aes(x = interaction(quarter,year), ...
得到的图形具有正确的顺序中的数据。
PS我建议的编辑(其中被拒绝到现在为止),并由于从小缺乏信誉的,我不允许发表评论,我宁可会做。
用户Tung
有一个伟大的答案在此线程
library(tidyverse)
library(lubridate)
library(scales)
set.seed(123)
df <- tibble(
date = as.Date(41000:42000, origin = "1899-12-30"),
value = c(rnorm(500, 5), rnorm(501, 10))
)
# create year column for facet
df <- df %>%
mutate(year = as.factor(year(date)))
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
scale_x_date(date_labels = "%b",
breaks = pretty_breaks(),
expand = c(0, 0)) +
# switch the facet strip label to the bottom
facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
labs(x = "") +
theme_classic(base_size = 14, base_family = 'mono') +
theme(panel.grid.minor.x = element_blank()) +
# remove facet spacing on x-direction
theme(panel.spacing.x = unit(0,"line")) +
# switch the facet strip label to outside
# remove background color
theme(strip.placement = 'outside',
strip.background.x = element_blank())
p