0

My problem is related to car package.

I create Kernal plot. However, since legend is too big, I would like to move legend outside the plot are, upper or lower? Otherwise, I tried with cowplot::get_legend( ), but it did not work properly.

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

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



  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Nov 01 '19 at 18:21

1 Answers1

0

Probably the easiest thing is to not plot the legend using the densityPlot() function but rather add it separately using legend(). The following code is an example of how this can be done. The resulting figure look like this:

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)
Calvin
  • 1,309
  • 1
  • 14
  • 25