Mat*_*unz 5 r ggplot2 stacked-area-chart
我用ggplot2创建了一个堆积区域图,并在其上的某些位置添加了垂直线x-axis.
我现在想要命名由这些垂直线分隔的部分.它的示例可能看起来像示例图中显示的那样.其他解决方案也欢迎.我有一个矢量breaks (x-axis)和一个间隔名称的矢量.
码:
library(ggplot2)
d <- read.delim(...)
x_breaks = c(-3999,1,599,4076,7557,11556)
png(output, width=800, height=400)
ggplot(d, aes(x=p, y=c, group=Groups, fill=Groups)) +
geom_area(position="stack") +
opts(title="testtestest",
...) +
scale_x_continuous(expand=c(0,0), breaks=x_breaks) +
scale_y_continuous(expand=c(0,0)) +
geom_vline(xintercept=x_breaks[which(x_breaks != min(x_breaks) & x_breaks != max(x_breaks))])
dev.off()
Run Code Online (Sandbox Code Playgroud)

没有数据,很难重现您的示例(您的休息时间等)。但是以下内容将帮助您入门。
一种相当简单的解决方案是使用ggplot2的annotate()功能在垂直线之间的中间位置向绘图面板添加文本注释。
# Load packages
library (ggplot2)
library(grid)
# Some data
df = data.frame(x = 1:10, y = 1:10)
# Base plot
p <- ggplot(df, aes(x,y)) + geom_point() +
scale_x_continuous(limits = c(0, 11), expand = c(0,0)) +
geom_vline(xintercept = 3) + geom_vline(xintercept = 7)
# Add the annotations
p + annotate("text", x = .5*(0+3), y = 11, label = "Part 1") +
annotate("text", x = .5*(3+7), y = 11, label = "Part 2") +
annotate("text", x = .5*(7+11), y = 11, label = "Part 3")
Run Code Online (Sandbox Code Playgroud)
结果是:

或者,就注释而言,最接近示例图的解决方案。它用于annotation_custom()绘制线条并将文本放置在打印面板之外。即使注释在绘图面板的外部绘制,注释的定位也取决于数据坐标。基本图中的下边距被加宽以为注释留出空间。该解决方案需要代码来覆盖ggplot对图元素到图面板的剪切。
opts不推荐使用更新;使用theme代替。
# Base plot
p <- ggplot(df, aes(x,y)) + geom_point() +
scale_x_continuous(limits = c(0, 11), expand = c(0,0)) +
geom_vline(xintercept = 3) + geom_vline(xintercept = 7) +
theme(plot.margin = unit(c(1,1,4,1), "lines"))
# Create the text Grobs
Text1 = textGrob("Part 1")
Text2 = textGrob("Part 2")
Text3 = textGrob("Part 3")
# Add the annotations
# Segment 1
p1 = p +
annotation_custom(grob = linesGrob(), xmin = 0, xmax = 0, ymin = -1, ymax = -.75) +
annotation_custom(grob = linesGrob(), xmin = 0, xmax = 3, ymin = -1, ymax = -1) +
annotation_custom(grob = linesGrob(), xmin = 3, xmax = 3, ymin = -1, ymax = -.75) +
annotation_custom(grob = Text1, xmin = 0, xmax = 3, ymin = -1.25, ymax = -1.25)
# Segment 2
p1 = p1 +
annotation_custom(grob = linesGrob(), xmin = 3, xmax = 7, ymin = -1, ymax = -1) +
annotation_custom(grob = linesGrob(), xmin = 7, xmax = 7, ymin = -1, ymax = -.75) +
annotation_custom(grob = Text2, xmin = 3, xmax = 7, ymin = -1.25, ymax = -1.25)
# Segment 3
p1 = p1 +
annotation_custom(grob = linesGrob(), xmin = 7, xmax = 11, ymin = -1, ymax = -1) +
annotation_custom(grob = linesGrob(), xmin = 11, xmax = 11, ymin = -1, ymax = -.75) +
annotation_custom(grob = Text3, xmin = 7, xmax = 11, ymin = -1.25, ymax = -1.25)
# Code to override clipping
gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Run Code Online (Sandbox Code Playgroud)
结果是:
