在R> lattice()> densityplot()如何在键中包含观察数?用auto.key()?

时间:2016-05-17 14:09:26

标签: r lattice density-plot

我目前正在使用以下内容绘制ROAS密度,按生成ROAS的年份(campaign.year)分组

densityplot(~roas,data=ndb.data.analysis,groups=campaign.year,plot.points=FALSE,auto.key = list(columns=4),main="Distribution of ROAS by Year",from=0,xlab="Return on Ad Spend ($)",ylab="Percent of Observations")

我想在关键字中指出每年的观察次数。

有这么好(简单)的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您没有提供数据,因此请使用内置数据集。使用key参数,您可以自定义图例。

library(lattice)
data(mtcars)

# number observations for each cylinder count
nobs = aggregate(mtcars$mpg,list(mtcars$cyl),length)
nobs # see results
# construct labels to include nobs
labels=paste0(levels(as.factor(mtcars$cyl))," (",nobs$x," obs.)")
linecolor = trellis.par.get("superpose.symbol")$col[1:length(labels)]
densityplot(~mpg,mtcars,groups=cyl,lwd=2,
key=list(space="right",adj=0,title="No. cylinders",
          lines=list(pch=1,col=linecolor,lwd=2),
          text=list(labels))
)