am3010
am3010

Reputation: 67

How to show just the legend in R?

I want to create a legend to depict what different colors mean. Like the image below: enter image description here

I'm able to achieve this by passing Null values to plot but the plot takes up a lot more white space around it. (Screenshot attached below). Is there any other way using which I can just show legend. enter image description here Here's the piece of code I used.

plot(NULL ,xaxt='n',yaxt='n',bty='n',ylab='',xlab='', xlim=0:1, ylim=0:1)
legend("topright", horiz = T, legend =c('Good', 'Bad', 'Poor'), pch=15, pt.cex=5, cex=1.5, bty='n', col = c('#3d9970','#ff851b', '#dd4b39'))

Upvotes: 1

Views: 288

Answers (1)

Kat
Kat

Reputation: 18714

You've already created it, so why create it again? If you want to use this image, but without all the added whitespace, you can trim out the whitespace using the magick package.

library(magick)

fig <- image_graph(width = 600, height = 400, res = 96)
plot(NULL ,xaxt='n',yaxt='n',bty='n',ylab='',xlab='', xlim=0:1, ylim=0:1)
legend("topright", horiz = T, legend =c('Good', 'Bad', 'Poor'), 
       pch=15, pt.cex=5, cex=1.5, bty='n', col = c('#3d9970','#ff851b', '#dd4b39'))
dev.off()

figT <- image_trim(fig)

enter image description here



Update

You asked if this could be done with HTML tags. This is an example of strictly HTML with inline CSS. (Ideally, CSS isn't inline.)

<div style="display: flex; align-items: center;">
  <div style="width: 20px; height: 20px; background: #3d9970;"></div>
  <p style="font-size: 20px; padding:0px 8px 0px 4px;">Good</p>
  <div style="width: 20px; height: 20px; background: #ff851b;"></div>
  <p style="font-size: 20px; padding:0px 8px 0px 4px;">Bad</p>
  <div style="width: 20px; height: 20px; background: #dd4b39;"></div>
  <p style="font-size: 20px; padding:0px 8px 0px 4px;">Poor</p>
</div>

Upvotes: 1

Related Questions