在ggplot中获取tick tick位置 [英] Get tick break positions in ggplot
问题描述
我创建了一个函数用于创建一个条形图,使用 ggplot
。
在我想叠加
p < - ggplot(iris, aes(x = Species,y = Sepal.Width))+
geom_bar(stat ='identity')
#通过检查,我发现y-tick位置是c(50,100,150)
p + geom_hline(aes(yintercept = seq(50,150,50)),color ='white')
然而,我希望能够要更改数据,所以我不能像示例中那样使用静态位置。例如,我可以在上面的示例中将 Sepal.With
更改为 Sepal.Height
。
你能告诉我如何:
- 从我的ggplot获取勾号位置;或
- 获取
ggplot
用于打勾位置的函数,以便我可以使用它来定位我的行。 b $ b
所以我可以做一些类似于
tickpositions< ; - ggplot_tickpostion_fun(iris $ Sepal.Width)
p + scale_y_continuous(breaks = tickpositions)+
geom_hline(aes(yintercept = tickpositions),color ='white')
$ c $ (1)的一个可能的解决方案是使用 ggplot_build $
ggplot_build
会产生[...]一个面板对象,其中包含所有关于break的信息。 ggplot_build(p)$ layout $ panel_ranges [[1]] $ y.major_source
#[1] 0 50 100 150
请参阅编辑 - ggplot2 2.2.0
替代。
I have created a function for creating a barchart using ggplot
.
In my figure I want to overlay the plot with white horizontal bars at the position of the tick marks like in the plot below
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')
However, I would like to be able to change the data, so I can't use static positions for the lines like in the example. For example I might change Sepal.With
to Sepal.Height
in the example above.
Can you tell me how to:
- get the tick positions from my ggplot; or
- get the function that
ggplot
uses for tick positions so that I can use this to position my lines.
so I can do something like
tickpositions <- ggplot_tickpostion_fun(iris$Sepal.Width)
p + scale_y_continuous(breaks = tickpositions) +
geom_hline(aes(yintercept = tickpositions), colour = 'white')
A possible solution for (1) is to use ggplot_build
to grab the content of the plot object. ggplot_build
results in "[...] a panel object, which contain all information about [...] breaks".
ggplot_build(p)$layout$panel_ranges[[1]]$y.major_source
# [1] 0 50 100 150
See edit for pre-ggplot2 2.2.0
alternative.
这篇关于在ggplot中获取tick tick位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!