在ggplot中获取tick tick位置 [英] Get tick break positions in ggplot

查看:219
本文介绍了在ggplot中获取tick tick位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个函数用于创建一个条形图,使用 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



你能告诉我如何:


  1. 从我的ggplot获取勾号位置;或

  2. 获取 ggplot 用于打勾位置的函数,以便我可以使用它来定位我的行。 b $ b

所以我可以做一些类似于

  tickpositions< ;  -  ggplot_tickpostion_fun(iris $ Sepal.Width)
p + scale_y_continuous(breaks = tickpositions)+
geom_hline(aes(yintercept = tickpositions),color ='white')
ggplot_build


解决方案 c $ c>来获取绘图对象的内容。 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:

  1. get the tick positions from my ggplot; or
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆