我想在每个点阵直方图面板上叠加一个额外的直方图(在每个面板中都是相同的)。我希望重叠的直方图具有实线边框但是空填充(col
),以便与基础直方图进行比较。
也就是说,最终结果将是一系列面板,每个面板具有不同的彩色直方图,并且每个面板在彩色直方图的顶部具有相同的额外轮廓直方图。
这是我尝试过的东西,但它只会产生空面板:
foo.df <- data.frame(x=rnorm(40), categ=c(rep("A", 20), rep("B", 20)))
bar.df <- data.frame(x=rnorm(20))
histogram(~ x | categ, data=foo.df,
panel=function(...){histogram(...);
histogram(~ x, data=bar.df, col=NULL)})
(我的猜测是我需要使用panel.superpose
,但这个功能有点令人困惑.Sarkar的书并没有解释如何使用它,R帮助页面没有例子。我发现在没有基本了解的情况下很难理解panel.superpose
帮助页面。我在网上找到的例子非常少,但我有我们无法弄清楚这些例子的哪些方面适用于我的案例。This answer肯定是相关的,但我不理解它对panel.groups
的使用,这个例子覆盖了三个不同的群体单个数据帧,而我想在多个也有不同数据的面板上重复覆盖相同的数据。)
答案 0 :(得分:0)
我继续研究这个问题,然后想出了答案。我一直在正确的轨道上,但错误地得到了几个重要的细节。下面代码中的注释说明了重点。
# Main data, which will be displayed as solid histograms, different in each panel:
foo.df <- data.frame(y=rnorm(40), cat=c(rep("A", 20), rep("B", 20)))
# Comparison data: This will be displayed as an outline histogram in each panel:
bar.df <- data.frame(y=rnorm(30)-2)
# Define some vectors that we'll use in the histogram call.
# These have to be adjusted for the data by trial and error.
# Usually, panel.histogram will figure out reasonable default values for these.
# However, the two calls to panel.histogram below may figure out different values,
# producing pairs of histograms that aren't comparable.
bks <- seq(-5,3,0.5) # breaks that define the bar bins
yl <- c(0,50) # height of plot
# The key is to coordinate breaks in the two panel.histogram calls below.
# The first one inherits the breaks from the top-level call through '...' .
# Using "..." in the second call generates an error, so I specify parameters explicitly.
# It's not necessary to specify type="percent" at the top level, since that's the default,
# but it is necessary to specify it in the second panel.histogram call.
histogram(~ y | cat, data=foo.df, ylim=yl, breaks=bks, type="percent", border="cyan",
panel=function(...){panel.histogram(...)
panel.histogram(x=bar.df$y, col="transparent",
type="percent", breaks=bks)})
# col="transparent" is what makes the second set of bars into outlines.
# In the first set of bars, I set the border color to be the same as the value of col
# (cyan by default) rather than using border="transparent" because otherwise a filled
# bar with the same number of points as an outline bar will be slightly smaller.