当x不连续时,我试图想出一种自动化x轴标签的方法。
我想做的事情有两件事:(1)在每年年底(每四个季度后)自动创建一条垂直线; (2)中心x轴标签,表示两条垂直线之间的年份(我使用空格来做)。下面代码的最后两行是我要做的。
require(ggplot2)
Quarter <- c("2010q1", "2010q2", "2010q3", "2010q4", "2011q1", "2011q2", "2011q3", "2011q4",
"2012q1", "2012q2", "2012q3", "2012q4", "2013q1", "2013q2", "2013q3", "2013q4")
rate <- c(1.6, 3.9, 2.8, 2.8, -1.3, 3.2, 1.4, 4.9,
3.7, 1.2, 2.8, 0.1, 1.1, 2.5, 4.1,2.6)
data <- data.frame(Quarter, rate)
ggplot(data, aes(x = Quarter, y = rate)) +
geom_bar(stat="identity", fill = "darkorange1") +
ylim(-10, 10) +
theme(axis.ticks.x = element_blank(),
axis.title = element_blank(),
axis.text.x = element_text(face = "bold"),
panel.background = element_rect(fill = "transparent", color = NA),
plot.background = element_rect(fill = "transparent", color = NA)) +
## THIS IS WHERE I NEED HELP -
geom_vline(xintercept = c(4.5, 8.5, 12.5, 16.5), linetype = 1,
size = 0.1, color = "grey20") +
scale_x_discrete(breaks=c("2010q2", "2011q2", "2012q2", "2013q2"),
labels = c(" 2010", " 2011", " 2012", " 2013"))
如果有更高效的方法,我将不胜感激。
答案 0 :(得分:1)
如果您将“Quarter”列中的数据拆分为“Year”和“YearQuarter”以进行两级分组,该怎么办?然后这个策略应该工作
require(ggplot2)
Year <- as.factor(rep(2010:2013, each=4))
YearQuarter <- rep(paste0("q",1:4), 4)
rate <- c(1.6, 3.9, 2.8, 2.8, -1.3, 3.2, 1.4, 4.9,
3.7, 1.2, 2.8, 0.1, 1.1, 2.5, 4.1,2.6)
data <- data.frame(rate, Year, YearQuarter)
然后用
绘制它ggplot(data, aes(x = Year, y = rate)) +
geom_bar(stat="identity", aes(group=YearQuarter),
fill = "darkorange1", width=.75, position=position_dodge(width=1)) +
ylim(-10, 10) +
theme(
axis.ticks.x = element_blank(),
axis.title = element_blank(),
axis.text.x = element_text(face = "bold"),
panel.background = element_rect(fill = "transparent", color = NA),
plot.background = element_rect(fill = "transparent", color = NA)) +
geom_vline(xintercept = 1:3+.5, linetype = 1,
size = 0.1, color = "grey20")
这就是这个情节