I could not display all the legends related to the plotted bars

6 次查看(过去 30 天)
When i run the simple code below i get the following error:
Warning: Ignoring extra legend entries.
> In legend>set_children_and_strings (line 643)
In legend>make_legend (line 328)
In legend (line 254)
In Data_calculation (line 18)
-------------Code-----------------
x=1:5;
y=[4.65,31.41,3.92,4.23,0.47];
b=bar(x,y,0.5,'stacked')
b =
Bar with properties: BarLayout: 'stacked' BarWidth: 0.5000 FaceColor: [0 0.4470 0.7410] EdgeColor: [0 0 0] BaseValue: 0 XData: [1 2 3 4 5] YData: [4.6500 31.4100 3.9200 4.2300 0.4700] Use GET to show all properties
grid on
ylabel('Output energy of the HRES components (MWh/year)')
set(gca, 'XTickLabel',{'PV','WT','Batt','DG','excess'}) %labeling x-axis
legend('PV','WT','Batt','DG','excess') %<-----------------% this is line 18
Warning: Ignoring extra legend entries.

采纳的回答

Dyuman Joshi
Dyuman Joshi 2024-3-24
You get a single legend entry because there is only a single graphical object.
If you want a separate legend for each bar, you need to plot them as separate bar objects.
One appoach to obtain that is as follows -
x=1:5;
y=[4.65,31.41,3.92,4.23,0.47];
%Modification
z = diag(y,0)
z = 5x5
4.6500 0 0 0 0 0 31.4100 0 0 0 0 0 3.9200 0 0 0 0 0 4.2300 0 0 0 0 0 0.4700
%Modified call to bar()
b=bar(x,z,0.5,'stacked')
b =
1x5 Bar array: Bar Bar Bar Bar Bar
As you can see, now there are 5 Bar objects created.
grid on
ylabel('Output energy of the HRES components (MWh/year)')
set(gca, 'XTickLabel',{'PV','WT','Batt','DG','excess'}) %labeling x-axis
legend('PV','WT','Batt','DG','excess') %<-----------------% this is line 18

更多回答(1 个)

Walter Roberson
Walter Roberson 2024-3-24
When y is an array, then one legend entry is created for each column of y
When y is a vector, then one legend entry total is created.
Legend entries are not created for each bar -- that's the role of the XTickLabel
x = 1:5;
y = rand(5,2);
b = bar(x,y,0.5,'stacked');
legend show

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

标签

产品


版本

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by