Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: how to read the scale transformation from a plot object

Tags:

r

ggplot2

r-s4

I'm trying to extract information about the limits and transform of an existing ggplot object. I'm getting close, but need some help. Here's my code

data = data.frame(x=c(1,10,100),y=(c(1,10,100)))
p    = ggplot(data=data,aes(x=x,y=y)) + geom_point()
p    = p + scale_y_log10()
q    = ggplot_build(p)
r    = q$panel$y_scales
trans.y = (q$panel$y_scales)[[1]]$trans$name
range.y = (q$panel$y_scales)[[1]]$rang

print(trans.y) gives me exactly what I want

[1] "log-10"

But range.y is a funky S4 object (see below).

> print(range.y)
Reference class object of class "Continuous"
Field "range":
[1] 0 2
> unclass(range.y)
<S4 Type Object>
attr(,".xData")
<environment: 0x11c9a0630>

I don't really understand S4 objects or how to query their attributes and methods. Or, if I'm just going down the wrong rabbit hole here, a better solution would be great :) In Matlab, I could just use the commands "get(gca,'YScale')" and "get(gca,'YLim')", so I wonder if I'm making this harder than it needs to be.

like image 484
Andy Stein Avatar asked Jan 26 '26 00:01

Andy Stein


1 Answers

As @MikeWise points out in the comments, this all becomes a lot easier if you update ggplot to v2.0. It now uses ggproto objects instead of proto, and these are more convenient to get info from.

It's easy to find now what you need. Just printing ggplot_build(p) gives you a nice list of all that's there.

ggplot_build(p)$panel$y_scales[[1]]$range here gives you a ggproto object. You can see that contains several parts, one of which is range (again), which contains the data range. All the way down, you end up with:

ggplot_build(p)$panel$y_scales[[1]]$range$range

# [1] 0 2

Where 0 is 10^0 = 1 and 2 is 10^2 = 100.

Another way might be to just look it up in $data part like this:

apply(ggplot_build(p)$data[[1]][1:2], 2, range)

#   y   x
# 1 0   1
# 2 1  10
# 3 2 100

You can also get the actual range of the plotting window with:

ggplot_build(p)$panel$ranges[[1]]$y.range

[1] -0.1  2.1
like image 78
Axeman Avatar answered Jan 28 '26 13:01

Axeman