Automagically Create Space at Top of Histogram for Inset Plot

25 views
Skip to first unread message

Brandon Hurr

unread,
Oct 21, 2013, 9:51:40 AM10/21/13
to ggplot2
Dears, 

I'm trying to add a subset histogram(s) at the top of my main histogram. I am able to do this with the following code. If I were to have a non-normal distribution, this inset plot would cover part of the main histogram. However, if I could programmatically add 20% to the y-axis I would be fine. The only way I can think of doing this is to dissect the ggplot_build() for the y_range, then adjust the y-scale. 

Is there a better way? 

p<-ggplot(data=mtcars, aes(x=mpg))+geom_histogram()

#dissect the guts for the range (default bins)
p.build<-ggplot_build(p)
p.build$panel$ranges[[1]]$y.range[2]

q<-p+scale_y_continuous(limits = c(0,p.build$panel$ranges[[1]]$y.range[2]*1.2))


grid.newpage()
vp_main<-viewport(width = 1, height = 1, x = 0.5, y = 0.5)
vp_inset<- viewport(width =0.2, height = 0.2, x = 0.13, y = 0.88)
print(q, vp=vp_main)
print(p, vp=vp_inset)

Thanks,

Brandon

baptiste auguie

unread,
Oct 21, 2013, 10:32:07 AM10/21/13
to Brandon Hurr, ggplot2
a lazy workaround would be to add a geom_blank layer with the same stat as the histogram layer, but data scaled up.

HTH,

b.


--
--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2
 
---
You received this message because you are subscribed to the Google Groups "ggplot2" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ggplot2+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Brandon Hurr

unread,
Oct 21, 2013, 10:51:52 AM10/21/13
to baptiste auguie, ggplot2
Baptiste, 

It's a good idea, but I can't seem to get it to work. Multiplying the source data affects the bins of the counts only subtly. I think I need to increase the counts somehow... 

ggplot(data=mtcars, aes(x=mpg))+
geom_histogram()+
geom_blank(data=mtcars, aes(x=mpg*20), stat="bin")


baptiste auguie

unread,
Oct 21, 2013, 11:12:05 AM10/21/13
to Brandon Hurr, ggplot2
how about increasing the binsize?

b.

baptiste auguie

unread,
Oct 21, 2013, 11:39:19 AM10/21/13
to Brandon Hurr, ggplot2
this seems to work,

geom_blank(data=mtcars, aes(y=2*..count..), stat="bin")

HTH,

b.

Brandon Hurr

unread,
Oct 21, 2013, 11:43:14 AM10/21/13
to baptiste auguie, ggplot2

On Mon, Oct 21, 2013 at 4:39 PM, baptiste auguie <baptist...@gmail.com> wrote:
geom_blank(data=mtcars, aes(y=2*..count..), stat="bin")

That is it. I kept trying to put ..count.. on the x variable. 
Thanks Baptiste. 

B
Reply all
Reply to author
Forward
0 new messages