简体   繁体   English

如何将图例放在 plot 区域之外?

[英]How to put legend outside the plot area?

My problem is related to car package.我的问题与汽车 package 有关。

I create Kernal plot.我创建了内核 plot。 However, since legend is too big, I would like to move legend outside the plot are, upper or lower?但是,由于图例太大,我想将图例移到 plot 之外,是上还是下? Otherwise, I tried with cowplot::get_legend( ), but it did not work properly.否则,我尝试使用 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))



Probably the easiest thing is to not plot the legend using the densityPlot() function but rather add it separately using legend() .可能最简单的事情不是 plot 使用densityPlot() function 的图例,而是使用legend()单独添加它。 The following code is an example of how this can be done.以下代码是如何完成此操作的示例。 The resulting figure look like this:结果图如下所示:

在此处输入图像描述

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM