Add small histogram inside plot area of another pl

2019-05-13 18:31发布

问题:

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")

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)

回答1:

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: