我想使用zig-zag函数在y轴底部添加grid到ggplot2图。这应该是通过从打印创建的gtable中检索轴grob并将点添加到水平线来实现的。
这是一个玩具示例:
library(ggplot2)
data(airquality)
data <- na.exclude(airquality)
model <- lm(Temp ~ Wind, data)
png(filename = "basic_plot.png", width=500, height=500, type = "cairo", res = 120)
ggplot(data=data, aes(y=Temp, x=Wind)) +
geom_point() +
geom_abline(intercept=coef(model)[1],
slope=coef(model)[2])+
theme_bw()
dev.off()
这是核心理念(对不起丑陋,Gimp不是理想的工具):
我需要帮助的工具是:
或者我已经开始查看ggplot代码,但我还没有找到创建轴grob的位置,理想情况下我想找到这些并添加一个允许这个的主题选项。
我知道Hadley的concerns添加了这个功能,但据我所知,这主要是在我同意的散点图的存在下。我的用例是生存曲线,通知底部不是0%非常重要。
导航视口树的核心功能是seekViewpor
,为了查看树,我们可以使用current.vpTree
:
library(grid)
current.vpTree()
# viewport[ROOT]->
# (viewport[GRID.VP.397]->(
# viewport[GRID.VP.398]),
# viewport[GRID.VP.399]->(viewport[GRID.VP.400]),
# viewport[GRID.VP.401]->(viewport[GRID.VP.402]),
# viewport[GRID.VP.404]->(viewport[GRID.VP.405]),
# viewport[layout]->(
# viewport[panel.6-4-6-4],
# viewport[subtitle.3-4-3-4],
# viewport[xlab-b.8-4-8-4]->(viewport[GRID.VP.397]->(viewport[GRID.VP.398])),
# viewport[axis-r.6-5-6-5],
# viewport[title.2-4-2-4],
# viewport[spacer.5-5-5-5],
# viewport[background.1-7-10-1],
# viewport[xlab-t.4-4-4-4],
# viewport[axis-l.6-3-6-3]->(
# viewport[GRID.VP.404]->(viewport[GRID.VP.405]),
# viewport[GRID.VP.406]->(
# viewport[GRID.VP.404]->(viewport[GRID.VP.405]),
# viewport[axis]->(
# viewport[axis.1-1-1-1]->(viewport[GRID.VP.404]->(viewport[GRID.VP.405])),
# viewport[axis.1-2-1-2]))),
# viewport[caption.9-4-9-4],
# viewport[ylab-l.6-2-6-2]->(viewport[GRID.VP.399]->(viewport[GRID.VP.400])),
# viewport[spacer.5-3-5-3],
# viewport[axis-b.7-4-7-4]->(
# viewport[GRID.VP.401]->(viewport[GRID.VP.402]),
# viewport[GRID.VP.403]->(viewport[GRID.VP.401]->(viewport[GRID.VP.402]),
# viewport[axis]->(
# viewport[axis.1-1-1-1],
# viewport[axis.2-1-2-1]->(
# viewport[GRID.VP.401]->(
# viewport[GRID.VP.402]))))),
# viewport[spacer.7-5-7-5],
# viewport[ylab-r.6-6-6-6],
# viewport[axis-t.5-4-5-4],
# viewport[spacer.7-3-7-3]))
评论是来自ggplot的美化输出。请注意,每个绘图都会更改一些数字,即GRID.VP。 397 会在绘图之间发生变化。我们现在可以导航到左轴并在y轴周围添加一个透明矩形:
seekViewport("axis-l.6-3-6-3")
grid.rect(gp = gpar(fill="#66666666"))
这导致:
剩下的问题是: