如何提取ggplot2对象的绘图轴范围? [英] How can I extract plot axes' ranges for a ggplot2 object?

查看:111
本文介绍了如何提取ggplot2对象的绘图轴范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自 ggplot2 ,例如 myPlot 的对象,我如何确定x和y的范围轴?



它似乎不是数据值范围的简单倍数,因为可以重新绘制绘图,修改轴的范围等等。 findFn (来自 sos )和Google似乎并没有提出相关结果,除了如何设置在新版本的ggplot2中,你可以在的输出中找到这些信息。

解决方案 ggplot_build(p),其中 p 是您的ggplot对象。 ggplot(< 0.8.9),下面的解决方案工作:



直到哈德利发布新版本,这可能会有所帮助。如果您未在图中设置限制,则ggplot对象中不会有任何信息。但是,在这种情况下,您可以使用ggplot2的默认值并从数据中获取xlim和ylim。

 > ggobj = ggplot(aes(x = speed,y = dist),data = cars)+ geom_line()
> ggobj $ coordinates $ limits

$ x
NULL

$ y
NULL

一旦您设置了限制,它们就可以在对象中使用:

 > bla = ggobj + coord_cartesian(xlim = c(5,10))
> bla $ coordinate $ limits
$ x
[1] 5 10

$ y
NULL


I have an object from ggplot2, say myPlot, how can I identify the ranges for the x and y axes?

It doesn't seem to be a simple multiple of the data values' range, because one can rescale plots, modify axes' ranges, and so on. findFn (from sos) and Google don't seem to be turning up relevant results, other than how to set the axes' ranges.

解决方案

In newer versions of ggplot2, you can find this information among the output of ggplot_build(p), where p is your ggplot object.

For older versions of ggplot (< 0.8.9), the following solution works:

And until Hadley releases the new version, this might be helpful. If you do not set the limits in the plot, there will be no info in the ggplot object. However, in that case you case you can use the defaults of ggplot2 and get the xlim and ylim from the data.

> ggobj = ggplot(aes(x = speed, y = dist), data = cars) + geom_line()
> ggobj$coordinates$limits

$x
NULL

$y
NULL

Once you set the limits, they become available in the object:

> bla = ggobj + coord_cartesian(xlim = c(5,10))
> bla$coordinates$limits
$x
[1]  5 10

$y
NULL

这篇关于如何提取ggplot2对象的绘图轴范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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