Exporting only the plot legend to a jpg file

81 views (last 30 days)
I have an odd case where I want to export the legend (only) of a plot to a jpeg file. That is, I don't what the whole figure, or even the axes - just the legend. It seems that exportgrpahics cannot do that. Is there another way, or do I have to resort to a screen shot :(
I'm running MATLAB Version: 9.8.0.1323502 (R2020a)

Accepted Answer

Nikhil Sapre
Nikhil Sapre on 25 Jun 2021
Hi Joe,
You can try something like this to turn of visibility of your plots, and axis object. This will export only the Legend from the figure.
clear all; close all;
figure;
p1 = plot([1:10], [1:10], '+-');
hold on;
p2 = plot([1:10], [1:10]+2, 'o--');
legend('text1', 'text2');
set(p1, 'visible', 'off');
set(p2, 'visible', 'off');
set(gca, 'visible', 'off');
exportgraphics(gcf,'test.jpg');
Thanks,
Nikhil.
  2 Comments
Heather
Heather on 15 Nov 2022 at 17:32
Edited: Heather on 15 Nov 2022 at 17:36
@Nikhil Sapre, this looks like a great solution. One question: I'm finding that the legend text looks a bit grayed out. (Using Matlab 2020b.) Do you have any tips on how to avoid that? I've tried explicitly noting 'TextColor','k' in the legend options but that doesn't seem to help.

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!