Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将文本添加到具有刻面密度的ggplot_R_Ggplot2_Facet - Fatal编程技术网

R 将文本添加到具有刻面密度的ggplot

R 将文本添加到具有刻面密度的ggplot,r,ggplot2,facet,R,Ggplot2,Facet,我在尝试用ggplot绘制密度图时遇到了一个问题。 数据看起来有点像这里的示例 require(ggplot2) require(plyr) mms <- data.frame(deliciousness = rnorm(100), type=sample(as.factor(c("peanut", "regular")), 100, replace=TRUE), color=sample(as.factor(c("r

我在尝试用ggplot绘制密度图时遇到了一个问题。 数据看起来有点像这里的示例

require(ggplot2)
require(plyr)
mms <- data.frame(deliciousness = rnorm(100),
                  type=sample(as.factor(c("peanut", "regular")), 100, replace=TRUE),
                  color=sample(as.factor(c("red", "green", "yellow", "brown")), 100, replace=TRUE))


mms.cor <- ddply(.data=mms, .(type, color), summarize, n=paste("n =", length(deliciousness)))

plot <- ggplot(data=mms, aes(x=deliciousness)) + geom_density() + facet_grid(type ~ color) + geom_text(data=mms.cor, aes(x=1.8, y=5, label=n), colour="black", inherit.aes=FALSE, parse=FALSE)
require(ggplot2)
需要(plyr)
彩信类似这样的内容

plot <- ggplot(data=mms, aes(x=deliciousness)) +
  geom_density(aes(y=..scaled..)) + facet_grid(type ~ color) +
  geom_text(data=mms.cor, aes(x=1.2, y=1.2, label=n), colour="black")
plot

基本思想是生成不带文本的
plot
,然后使用
ggplot\u build(plot)
构建图形对象。由此,我们可以提取x和y限制,并将其绑定到
mms.cor
数据帧中的标签。现在使用这些限制,使用文本渲染绘图


请注意,绘图与我之前的回答不同,因为您没有在代码中使用
set.seed(…)
来生成数据集(我忘记添加它了…。

在您的解决方案中,每个方面的比例都是相同的。我希望每个方面都有不同的比例(scales=“free”),然后将文本放置在每个方面的相同位置。所以我有不同的高度和宽度。谢谢你的建议。是的,你是最后一个做这项工作的人。构建图形,提取限制,并将其与包含这些限制的新数据框、一列(包含面名称)和我要添加的文本一起使用。非常好,谢谢你的解决方案,因为你是新来的,所以,请。一个非常好的解决方案,如果facet scales设置为“free”,它也可以工作。
plot <- ggplot(data=mms, aes(x=deliciousness)) +
  geom_density() + 
  facet_grid(type ~ color, scales="free")
panels <- ggplot_build(plot)[["panel"]]
limits <- do.call(rbind,lapply(panels$ranges,
                               function(range)c(range$x.range,range$y.range)))
colnames(limits) <- c("x.lo","x.hi","y.lo","y.hi")
mms.cor <- cbind(mms.cor,limits)
plot + 
  geom_text(data=mms.cor, aes(x=x.hi, y=y.hi, label=n), hjust=1,colour="black")