MATLAB: How to get the colors in the legend to not all be the same

colorlegendyyaxis

Here is my code to plot the data. The colors for the different plots in the graph are correct but they are all the same color in the legend (same color as first plot, green). This was working fine until I added a second y-axis.
yyaxis left
hold on
plot(X, VoltVar(:,1:13),'*','MarkerSize',8,'Color','g');
plot(Y,Z_SMA,'b');
ylabel('Reactive Power (VAr)');
yyaxis right
plot(X,activePower(:,1:13),'-','MarkerSize',8,'Color','r');
ylabel('Active Power (W)');
hold off
xlabel('Nominal Voltage % (208V)');
grid on
title('Volt-Var Test');
legend('SMA 7.0','IEEE 1547','Active Power');

Best Answer

By using plot handles in your call to legend().
p1 = plot(X, VoltVar(:,1:13),'*','MarkerSize',8,'Color','g');
p2 = plot(Y,Z_SMA,'b');
p3 = plot(X,activePower(:,1:13),'-','MarkerSize',8,'Color','r');
Then call legend with handle inputs
legend([p1(1), p2(1), p3(1)], {'SMA 7.0','IEEE 1547','Active Power'});
Alternatively, you could use this file submission along with the 'DisplayName' property.
Related Question