如何将图例放置在情节区域之外?

时间:2019-11-01 18:04:51

标签: r plot kernel-density

我的问题与汽车包装有关。

我创建核心图。但是,由于图例太大,我想将图例移到情节之外,是上还是下? 否则,我尝试使用cowplot :: get_legend(),但无法正常工作。

library(car)
mtcars$g <- as.factor(mtcars$vs)

densityPlot(mpg,mtcars$g,show.bw=T, kernel=depan,legend=list(location="topleft",title=NULL))



1 个答案:

答案 0 :(得分:0)

最简单的方法可能是不使用densityPlot()函数绘制图例,而是使用legend()单独添加图例。以下代码是如何完成此操作的示例。结果图如下:

enter image description here

library(car)
mtcars$g <- as.factor(mtcars$vs)

par(mar=c(4,4,4,2))
# obtaining results from kernel density and saving results
# need saved values for bandwidth in legend
# also plots the kernel densities
d <- densityPlot(mtcars$mpg,mtcars$g
            ,show.bw=T
            ,kernel=depan
            ,legend=F # no default legend
            ,col = c('black','blue')
            ,lty=c(1,2))

# allows legend outside of plot area to be displayed
par(xpd=T)
# defining location based on the plot coordinates from par('usr')
legend(x=mean(par('usr')[c(1,2)]) # average of range of x-axis
       ,y=par('usr')[4]+0.015 # top of the y axis with additional shift
       ,legend = c(paste('0 (bw = ',round(d$`0`['bw'][[1]],4),')',sep='') # extract bw values from saved output and
                   ,paste('1 (bw = ',round(d$`1`['bw'][[1]],4),')',sep='')) # formatting similar to default, except with rounding bw value
       ,ncol=1 # change to 2 if you want entries beside each other
       ,lty=c(1,2) # line types, same as above
       ,col=c('black','blue') # colors, same as above
       ,lwd=1
       ,xjust = 0.5 # centers legend at x coordinate
       ,yjust = 0.5 # centers legend at y coordinate
       )

par(xpd=F)