3

Is there a way to add a histogram inside the plot area of another plot, but independent of the "base" plot's coordinate system? In my case, I want to add a histogram as a legend to a choropleth map (the histogram would show the number of regions that fall in each class), but the question could just as easily apply to any plot. For example

plot(1:10)
rect(1, 7, 4, 9, col="gray")

enter image description here

Could I make a histogram appear where the gray rectangle is in the above plot? Currently, if I try to create a histogram of the series 1:10, it appears using the coordinate system set by the scatterplot, and I can't figure out how (or whether it is possible) to reposition it and resize it to appear in the top left.

plot(1:10)
hist(1:10, col="gray90", add=TRUE)

enter image description here

Lee Hachadoorian
  • 364
  • 2
  • 15
  • 1
    Have you tried the answers to [this question](http://stackoverflow.com/q/14288194/1036500)? Or [this](http://learnr.wordpress.com/2009/05/08/ggplot2-plot-inside-a-plot/) for `ggplot2` – Ben Jan 03 '14 at 04:17
  • I had not, but now I have. par(fig=...) is perfect. I also tried messing around with layout() and was making progress, but I think fig might be easier. – Lee Hachadoorian Jan 03 '14 at 05:24

1 Answers1

5

Try subplot in the TeachingDemos package (and also replicated in the Hmisc package). subplot takes user coordinates but grconvertX / grconvertY can be used to convert from normalized plot coordinates. See comments below for additional discussion.

library(TeachingDemos)
plot(1:10)
subplot(hist(1:10), grconvertX(c(.1, .4), "npc"), grconvertY(c(.7, .9), "npc"))

which gives:

enter image description here

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • I also found a subplot() function in the Hmisc package. The only problem I found was that I was creating a custom axis with separate calls to hist(..., axes=FALSE) followed by axis(...). This required two subplot calls, and I couldn't figure out how to get the subplot(axis(...)) call to appear in the right position relative to subplot(hist(...)). – Lee Hachadoorian Jan 03 '14 at 07:52
  • Try this: `plot(1:10); subplot( { hist(1:10, axes = FALSE); axis(1) }, grconvertX(c(.1, .4), "npc"), grconvertY(c(.7, .9), "npc"))`. Note that the `subplot` function in Hmisc is taken from TeachingDemos. – G. Grothendieck Jan 03 '14 at 12:04
  • G, that worked perfectly. I've made some edits to your answer. I would like to include the info about multiple functions as well, which is super-useful. Possibly beyond the scope of the original question, but it does make the answer complete. – Lee Hachadoorian Jan 04 '14 at 06:55