How to add a legend for bar and line plot on one figure?
6 次查看(过去 30 天)
显示 更早的评论
I have a graph which represents 8 different variables (4 bars, 4 line graphs). I would like to add a legend with these 8 variables. But when I type:
legend('A','B','C','D','E','F','G');
all my variables are represented in legend as bars (using gray rectangle like data1-data4 in the image attached below).
When I use Figure>Insert>Legend then graphical representing of my variables is fine, but then I cannot change the description of variables which is as follow:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/149533/image.png)
How to change description of data1-data8 or what should I change in my code to have my last 4 variables represented as lines (like in the image above)?
0 个评论
回答(2 个)
Thorsten
2015-9-29
x = rand(10, 4);
h(:, 1) = bar(x)
h(:, 2) = plot(x)
legend(h(:), {'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H'})
0 个评论
Sveinung Attestog
2022-1-13
I guess for you this answer is coming way to late. But for others that might ask this question in the future. There is an example in Matalb help. Just type "help legend" in command window and you will find it or copy paste below. What you need to do is to define the plots as matlab variables. Then you use your chosen variable names for the plots as the inut in legend at the beginning insided [....].
Examples:
x = 0:.2:12;
Y = [besselj(1,x); besselj(2,x); besselj(3,x)];
plot(x,Y);
legend('First','Second','Third','Location','NorthEastOutside')
b = bar(rand(10,5),'stacked');
hold on
ln = plot(1:10,5*rand(10,1),'-o');
hold off
legend([b,ln],'Carrots','Peas','Peppers','Green Beans',...
'Cucumbers','Eggplant')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!