Home > OS >  Two y-axis in Matlab: Setting different ranges and color
Two y-axis in Matlab: Setting different ranges and color

Time:03-01

I am a noob when it comes to Matlab and I would appreciate any help! I need to create a figure with two y axis, and in order to satisfy my tutors I have to use specific ranges for them, and also to make it "more appealing" use colours that make some sense.

So I have two questions:

First, how can I set different ranges for the two y axis? I know I can use ylim([]} easily for 1 y axis but that doesn't seem to work.

Secondly, how can I easily change the color and format of one plot?(preferably they are the same as the color of the y axis they are assigned to, but Matlab automatically chooses them weirdly) Sadly sth like this won't work:

plot(x,y,'r','-','LineWidth',2.0);

It would be perfect if the first and second plot have the same format so '-' and the third and fourth another e.g. '--' but the plots Colors stay the same as their respective axis.

This is my current figure: First Version

The following is my code

clc

A=dlmread('bipsim2_220.txt');
B=dlmread('bipsim2_680.txt');

x=A(:,1);
y=A(:,3);
plot(x,y,'LineWidth',2.0);
yyaxis left

hold on

x2=A(:,1);
y2=A(:,2);
plot(x2,y2,'LineWidth',2.0);
yyaxis right

hold on

x3=B(:,1);
y3=B(:,3);
plot(x3,y3,'LineWidth',2.0);
yyaxis left

hold on

x4=B(:,1);
y4=B(:,2);
plot(x4,y4,'LineWidth',2.0);
yyaxis right

yyaxis left
ylabel('Verstärkung (dB)')

yyaxis right
ylabel('Phase (deg)')

ylabel('Freq (Hz)')

set(gca,'Xscale','log')

set(gca,'fontsize',18)

hold off

grid minor
legend('R48/220 Ω: Phase [deg]','R48/220 Ω: Gain [dB]','R51/680 Ω: Phase [deg]','R51/680 Ω: Gain [dB]')

Thanks in advance for any help!

CodePudding user response:

  • You can specify colors using RGB tuple with the color keyword agrument
  • You can specify linewidth using the linewidth keyword argument
  • You can specify styles as a positional argument after the data.
  • You can easily get X with logscale using semilogx
  • twinx will create a secondary Y-axis on with the labels on the right sharing the same X-axis.
import numpy as np
import matplotlib.pyplot as plt
freq = np.logspace(0, 5) # your frequency grid
# I made up a transfer function
H = lambda s: (s**2 - 1e2*s   1e2) / (s - 1e3)**2 
g = H(2j * np.pi * freq); # evaluate the transfer function at the frequency grid
# plot
plt.semilogx(freq, 20 * np.log10(abs(g)), '--k', linewidth=2)
plt.ylabel('Gain [dB]')
plt.xlabel('Frequency [Hz]');
plt.grid()
plt.twinx()
plt.semilogx(freq, 180 * np.angle(g) / np.pi, '-', linewidth=2, color=[0.8, 0.5, 0.3])
plt.ylabel('Phase [degrees]')

how it looks

you can also specify predefined colors e.g k for black.

CodePudding user response:

A few things to note:

  • You only need to call hold on once on the figure. Everything plotted after the first hold on will keep in the plot until you clear it with clf.
  • You can specify color and line style for each of your plots individually in its respective call to plot(...)
  • You need to set yyaxis left or yyaxis right before the thing you want to appear on that axis. This Matlab "from now on, we're now going to use the left/right axis"
  • On the same note, once you've set the approriate axis, you can manipulate its color and range.

In your code (untested because I don't have your input text files):

A=dlmread('bipsim2_220.txt');
B=dlmread('bipsim2_680.txt');

% resorted to have data and plotting separate (no need to do this, just easier to read the plotting part)
x1=A(:,1);
y1=A(:,3);
x2=A(:,1);
y2=A(:,2);
x3=B(:,1);
y3=B(:,3);
x4=B(:,1);
y4=B(:,2);

% set colors as a variables to change them easier
colorLeft = 'r'; % red
colorRight = 'k'; % black

% let's just open a clean figure
clf;

% set hold to on
hold on;

%% do stuff for the left y axis (gain)
yyaxis left;

% plot data with respective color and line style
plot(x1,y1,'LineWidth',2.0, 'Color', colorLeft, 'LineStyle', '-');
plot(x3,y3,'LineWidth',2.0, 'Color', colorLeft, 'LineStyle', '--');
% axis formating
ylabel('Verstärkung (dB)');
ylim([-200, 50]); % chose lower and upper limit for left y-axis 
ax = gca; % all the formating of the axis is stored in an axis object which we can manipulate
ax.YColor = colorLeft; % set color of current (i.e. left) y-axis

%% now we move to do stuff for the right y axis (phase)
yyaxis right;

% plot data with respective color and line style
plot(x2,y2,'LineWidth',2.0, 'Color', colorRight, 'LineStyle', '-');
plot(x4,y4,'LineWidth',2.0, 'Color', colorRight, 'LineStyle', '--');
% axis formating
ylabel('Phase (deg)');
ylim([-180, 0]); % chose lower and upper limit for right y-axis 
ax.YColor = colorRight; % set color of current (i.e. right) y-axis

%% finally, set all the format stuff not related to a particular y-axis
xlabel('Freq (Hz)')
ax.XScale = 'log';
ax.FontSize = 18;
grid minor

% hold off % no need to turn hold off, its only affecting the current figure anyway

%make sure that the order of legend entries fits the order in which you plot the curves
legend('R48/220 Ω: Gain [dB]','R51/680 Ω: Gain [dB]', 'R48/220 Ω: Phase [deg]','R51/680 Ω: Phase [deg]'); 
  • Related