Matlab - axes properties - matlab

How to make x-axis and y-axis cross at origin and label the axes in both sides, i.e 'xlabel' in +ve x-axis and 'xlabel' in -ve x-axis and similarly for 'ylabel'.

You can use the function drawaxis taken here to position the x- and y- axis. Then you can add text annotations as labels. The function does have a few limitations but that's very easy to use.
clear
clc
close all
x = -10:10;
y = rand(size(x))-.5;
plot(x,y)
%// Here the axes cross at(0,0)
drawaxis(gca, 'x', 0,'y',0)
text(5,-.05,'+ axis','HorizontalAlignment','center')
text(-5,-.05,'- axis','HorizontalAlignment','center')
Output:

Related

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

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:
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!
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]')
you can also specify predefined colors e.g k for black.
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]');

How to scale vertical axis in increasing order from Bottom to Top in Matlab?

clear all;close all;clc
x =linspace(pi,2*pi,20)
y =linspace(0,pi,20)
C = [1 2];
imagesc(x,y,C)
colorbar
The vertical axis is not increasing from bottom to top.
May I know how to fix this? I have tried using flipr() so that vertical axis increase from bottom to top.
You are using an image, thus the axis are in image mode, where the coordinates start on the top left.
imagesc and other image showing functions automatically call axis image;. You can change that to the normal axis by calling axis xy; after the imagesc call.
You can also change the direction of the y axis (or any axis) by changing the YDir property.
% Get the handle to the axes
ax = gca;
% Change the y axis direction
ax.YDir = 'normal';

Same x-axis for two different subplots in MATLAB

I want have a line and bar plot in a figure in MATLAB. How can I have same x-axis for both graphs? The below bar plot x-axis should be same as above x-axis. I want retain the ability of comparing figures.
Figure link: Click Here
You can use linkaxes function:
figure
ax1 = subplot(2,2,1);
x1 = linspace(0,6);
y1 = sin(x1);
plot(x1,y1)
ax2 = subplot(2,2,2);
x2 = linspace(0,10);
y2 = sin(2*x2);
plot(x2,y2)
ax3 = subplot(2,2,[3,4]);
x3 = linspace(0,16);
y3 = sin(6*x3);
plot(x3,y3)
linkaxes([ax1,ax2,ax3],'x')
usage:
linkaxes(ax) links the x- and y-axis limits of the Axes objects specified
in the vector ax. The linkaxes function chooses limits that incorporate the
current limits for all the linked axes.
linkaxes(ax, option) links the axes ax according to the specified option.
The option argument can be one of these values:
'x' Link x-axis only.
'y' Link y-axis only.
'xy' Link x-axis and y-axis.
'off' Remove linking.
Reference here: https://www.mathworks.com/help/matlab/ref/linkaxes.html
If you have a matlab older than 2006 you can follow this: https://www.mathworks.com/matlabcentral/fileexchange/7169-samexaxis-nice-subplots-with-same-x-axis

Align inset in matlab plot to the right

How can I align an inset of a MATLAB plot to the top right edge of the box, like in the picture?
The example was generated with GNU R as explained in How to add an inset (subplot) to "topright" of an R plot?
Here is a way to do it:
Basically create a figure with an axes, and then add a new axis that you place to a specific position and to which you give the size you want.
Code:
clc
clear
close all
%// Dummy data
x = -20:0;
x2 = x(5:10);
%// Zoomed region to put into inset.
y = x.^2;
y2 = y(5:10);
%// Create a figure
hFig = figure(1);
%// Plot the original data
hP1 = plot(x,y);
xlabel('Original x','FontSize',18)
ylabel('Original y','FontSize',18)
hold on
%// Add an axes and set its position to where you want. Its in normalized
%// units
hAxes2 = axes('Parent',hFig,'Position',[.58 .6 .3 .3]);
%// Plot the zommed region
plot(x2,y2,'Parent',hAxes2)
%// Set the axis limits and labels
set(gca,'Xlim',[x(5) x(10)])
xlabel('Zoomed x','FontSize',16)
ylabel('Zommed y','FontSize',16)
And output:
To be fancy you could play around with the new axes position so that the outer borders coincide with the large one, but that should get you going :)

Adding an x axis label with 2 y axis labels

I can add 2 y-axis to a octave/matlab plot but when I try and add the x-axis at the bottom of the plot with xlabel('Frequency in Hz') it doesn't show up
[ax h1 h2]=plotyy(xx,yy,xx,yy2); %plot two y axes and 1 x-axis
axes(ax(1)); ylabel('Phase Angle in degrees');
axes(ax(2)); ylabel('Amplitude');
Anybody know how to fix this so the x-axis will also show up
I'm using octave 3.2.4 / matlab
Make sure to call xlabel() after referencing one of the specific axes on the plot. You just need to do it once, but because of the double axis, invoking x-label outside of a specific axis context won't work. The following works for me just fine in Octave 3.2.4.
xx = [1,2,3];
yy = [10,11,12];
yy2 = [-10,-11,-12];
[ax h1 h2]=plotyy(xx,yy,xx,yy2);
axes(ax(1)); xlabel('Frequency in Hz'); ylabel('Phase Angle in degrees');
axes(ax(2)); ylabel('Amplitude');
In order to add a label (either xlabel or ylabel) to certain axes you can also pass this axes reference as first argument of the command call. This way you will also guarantee that you are on the right context as #EMS pointed out.
xx = [1,2,3];
yy = [10,11,12];
yy2 = [-10,-11,-12];
[ax h1 h2]=plotyy(xx,yy,xx,yy2);
xlabel(ax(1),'Frequency in Hz'); ylabel(ax(1),'Phase Angle in degrees');
ylabel(ax(2),'Amplitude');
This is also better in terms of performance, as in case you call axes several times, you will see how everything slows considerably down.