获取ggplot中的tick tick位置

问题描述 投票:6回答:4

我创建了一个使用ggplot创建条形图的功能。

在我的图中,我想在刻度线的位置用白色水平条覆盖图,如下图所示

p <- ggplot(iris, aes(x = Species, y = Sepal.Width)) + 
geom_bar(stat = 'identity')
# By inspection I found the y-tick postions to be c(50,100,150)
p + geom_hline(aes(yintercept = seq(50,150,50)), colour = 'white')

但是,我希望能够更改数据,因此我不能像示例中那样使用静态位置。例如,我可能会在上面的例子中将Sepal.With更改为Sepal.Height

你能告诉我怎么做:

  1. 从我的ggplot中获取刻度位置;要么
  2. 获得ggplot用于刻度位置的功能,以便我可以使用它来定位我的线。

所以我可以做点什么

tickpositions <- ggplot_tickpostion_fun(iris$Sepal.Width)
p + scale_y_continuous(breaks = tickpositions) +
geom_hline(aes(yintercept = tickpositions), colour = 'white')
r ggplot2 bar-chart
4个回答
8
投票

(1)的可能解决方案是使用ggplot_build来获取绘图对象的内容。 ggplot_build导致“[...]面板对象,其中包含有关[...]休息的所有信息”。

ggplot_build(p)$layout$panel_ranges[[1]]$y.major_source
# [1]   0  50 100 150

请参阅编辑pre-ggplot2 2.2.0替代方案。


2
投票

查看ggplot2::ggplot_build - 它可以显示有关绘图对象的大量详细信息。你必须给它一个绘图对象作为输入。我通常喜欢str() ggplot_build的结果,看看它有什么不同的价值。

例如,我看到有一个panel --> ranges --> y.major_source矢量似乎是你正在寻找的。所以要完成你的例子:

p <- ggplot() +
    geom_bar(data = iris, aes(x = Species, y = Sepal.Width), stat = 'identity')
pb <- ggplot_build(p)
str(p)
y.ticks <- pb$panel$ranges[[1]]$y.major_source
p + geom_hline(aes(yintercept = y.ticks), colour = 'white')

请注意,我将数据参数从主ggplot函数移动到geom_bar内部,因此当iris中的数字不是我们绘制的行数的倍数时,geom_line不会尝试使用相同的数据集并抛出错误。另一种选择是将data = data.frame()论证传递给geom_line;我无法评论哪一个是更正确的解决方案,或者是否有一个更好的解决方案。但我的代码的要点仍然是:)


0
投票

对于ggplot 3.1.0,这对我有用:

ggplot_build(p)$layout$panel_params[[1]]$y.major_source
#[1]   0  50 100 150

-2
投票

你肯定可以。阅读seq()函数的帮助文件。

seq(from = min(), to = max(), len = 5)

并做这样的事情。

p <- ggplot(iris, aes(x = Species, y = Sepal.Width)) + 
geom_bar(stat = 'identity')
p + geom_hline(aes(yintercept = seq(from = min(), to = max(), len = 5)), colour = 'white')
© www.soinside.com 2019 - 2024. All rights reserved.