Plotting two different plots(y axes), sharing the same x in matlab - matlab

Considering this question, I am trying to Tackling the issue with two separate plots using axes instead of plotyy which doesn't work well with 'boxplot' and 'plot':
%%% definition of my x=y line axes
y2 = 1:6;
x2 = 1:6;
% Plot the first data set using boxplot, that results in 6 boxes
load carsmall;
boxplot(MPG,Origin)
% Get the axes and configure it
ax1 = gca;
set(ax1,'XColor','r','YColor','r')
%Create the new axes
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','top',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k','YColor','k');
% Plot the second data set with the new axes
hl2 =plot(x2,y2,'Color','k','parent',ax2);
but still I dont get my final plot in a right way. Does anyone know why?

There is a hold on missing before the last line.

Related

Graphs is not plotting properly in the subplot in MATLAB

I have I have a data file which has 3 columns, 1st column is the field for the data, or you can say different index. 2nd column is the x-axis data, and the 3rd column is the y-axis data. Now I have similar data files for different variables like 8 files. I want to plot all the graph in one figure in MATLAB. For my problem, I am showing only one subplot. This subplot data file should plot 5 "line plots" for 5 indexes (1st column). But when I plot it as subplot it shows only 1 plot. here is my code in the below:
% open Zdiff Odd Mode data file
fid = fopen('Data_test.txt');
% Read data in from csv file
readData = textscan(fid,'%f %f %f','Headerlines',1,'Delimiter',',');
fclose(fid);
% Extract data from readData
index_Data = readData{1,1}(:,1);
% Identify the unique indices
uni_idx=unique(index_Data);
xData = readData{1,2}(:,1);
yData = readData{1,3}(:,1);
% Plot Data
f = figure;
%Top Title for all the subplots
p = uipanel('Parent',f,'BorderType','none');
p.Title = 'Electrical Characteristics';
p.TitlePosition = 'centertop';
p.FontSize = 14;
p.FontWeight = 'bold';
cla; hold on; grid on, box on;
ax1 = subplot(2,4,1,'Parent',p);
% Loop over the indices to plot the corresponding data
for i=1:length(uni_idx)
idx=find(index_Data == uni_idx(i));
plot(xData(idx,1),yData(idx,1))
end
The plot results like below:
When I plot the data as a full figure, the plot is perfect. But as I have lots of data to plot in one figure as subplots, I need to know what is wrong in my subplot code.
Here is my code for the whole figure of the data without the subplot
Before plotting code it is same as before:
% Plot Data
f1 = figure(1);
cla; hold on; grid on;
% Loop over the indices to plot the corresponding data
for i=1:length(uni_idx)
idx=find(index_Data == uni_idx(i));
plot(xData(idx,1),yData(idx,1))
end
The resulting figure is below:
What is wrong with my plotting code in the subplot? Can anyone help me out?
This is your sequence of commands, and what they do:
f = figure;
Creates an empty figure, there are no axes yet defined here.
cla
Clears the current axes, since there is no current axes, it creates one.
hold on
Sets the "hold" property on the current axes
grid on, box on
Sets some other properties of the current axes
ax1 = subplot(2,4,1,'Parent',p);
Creates new axes. Because it overlays the previously created axes, those are deleted.
plot(xData(idx,1),yData(idx,1))
Plots to the current axes (i.e. the one created by subplot). These axes don't have the "hold" property set, so subsequent plot commands will overwrite the data plotted here.
The solution, as suggested by Ander in a comment, is to set the "hold" property of the axes created by subplot. Replace:
cla; hold on; grid on, box on;
ax1 = subplot(2,4,1,'Parent',p);
with:
ax1 = subplot(2,4,1,'Parent',p);
hold on; grid on, box on;
(note that cla is not necessary, since you're drawing to a new, empty figure).

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

How to add new plots of different scale to an existing histogram?

I have a Matlab figure with two histograms on it
,
created with hist() function. Now I want to add two plots in the same figure (bell distribution actually:
,
but they have different scale. I thought I could use plotyy, but I already have my first plot-scale on the figure. How can I add the second plot-scale?
Generally, this is one way to do it:
%// example data
rng(0,'twister')
data = randn(1000,3);
x = linspace(-4,4,100);
y = 16 - x.^2;
%// generate two axes at same position
ax1 = axes;
ax2 = axes('Position', get(ax1, 'Position'),'Color','none');
%// move second axis to the right, remove x-ticks and labels
set(ax2,'YAxisLocation','right')
set(ax2,'XTick',[])
%// plot hist and line plot
hist(ax1,data); hold on
plot(ax2,x,y)
ylabel(ax1,'label of hist')
ylabel(ax2,'label of plot')
xlabel(ax1,'Hello World!')

Overlaying two axes in a Matlab plot

I am looking for a way to overlay an x-y time series, say created with 'plot', on top of a display generated by 'contourf', with different scaling on the y-axes.
It seems that the typical way to do this in the case of two x-y plots is to use the built-in function 'plotyy', which can even be driven by functions other than 'plot' (such as 'loglog') as long as the input arguments remain the same (x,y). However, since in my case contourf requires three input arguments, 'plotyy' seems to not be applicable. Here is some sample code describing what I would like to do:
x1 = 1:1:50;
y1 = 1:1:10;
temp_data = rand(10,50);
y2 = rand(50,1)*20;
figure; hold on;
contourf(x1,y1,temp_data);
colormap('gray');
plot(x1,y2,'r-');
Ideally, I would like the timeseries (x1,y2) to have its own y-axes displayed on the right, and be scaled to the same vertical extent as the contourf plot.
Thanks for your time.
I don't think there's a "clean" way to do this, but you can fake it by overlaying two axes over each other.
x1 = 1:1:50;
y1 = 1:1:10;
temp_data = rand(10,50);
y2 = rand(50,1)*20;
figure;
contourf(x1, y1, temp_data);
colormap('gray');
h_ax = gca;
h_ax_line = axes('position', get(h_ax, 'position')); % Create a new axes in the same position as the first one, overlaid on top
plot(x1,y2,'r-');
set(h_ax_line, 'YAxisLocation', 'right', 'xlim', get(h_ax, 'xlim'), 'color', 'none'); % Put the new axes' y labels on the right, set the x limits the same as the original axes', and make the background transparent
ylabel(h_ax, 'Contour y-values');
ylabel(h_ax_line, 'Line y-values');
In fact, this "plot overlay" is almost definitely what the plotyy function does internally.
Here's example output (I increased the font size for legibility):

plotting two yaxis with different markers and colors

If I have two y vectors and one x vector:
y1 = [0.1,0.2,0.5,0.6];
y2 = [0.3,0.4,0.7,0.8];
x = 1:length(y1);
How can I plot all of the information on the same plot using different markers and different colors. I have tried the following:
cols = {'k','r','b',[0,0.5,0]};
markers = {'s','o','d','v'};
for i = 1:4;
plot(x(i),y1(i),markers{i},'color',cols{i},'MarkerEdgeColor',...
cols{i},'MarkerFaceColor','w');
hold on
end
ax1 = gca;
ax2 = axes('Position',get(ax1,'Position'),...
'YAxisLocation','right','XColor','k','YColor','k');
linkaxes([ax1,ax2],'x');
for i = 1:4;
plot(x(i),y2(i),markers{i},'color',cols{i},'MarkerEdgeColor',...
cols{i},'MarkerFaceColor',cols{i},'Parent',ax2);
hold on;
end
But this seems to overwrite the first plot. My aim here it to draw the first four points (y1) with the markers and colors defined, but with the maker faces in white. I then hope to include on the same figure, a second yaxis (on the right) with the values from y2, but this time with the marker faces colored according to 'cols'. How can I do this?
Addition:
When I use plotyy
for i = 1:4;
[ax,h1,h2] = plotyy(x(i),y1(i),x(i),y2(i));
hold on
set(h1,'linestyle','none','marker',markers{i},'MarkerEdgeColor',...
cols{i},'MarkerFaceColor',cols{i});
set(h2,'linestyle','none','marker',markers{i},'MarkerEdgeColor',...
cols{i},'MarkerFaceColor','w');
set(ax,{'ycolor'},{'k';'k'},{'xcolor'},{'k';'k'});
end
The xaxis values do not show up correctly, where although they are identical, they do not line up on the plot.
You can use the embedded function of Matlab , plotyy
plotyy(X1,Y1,X2,Y2) plots X1 versus Y1 with y-axis labeling on the left and plots X2 versus Y2 with y-axis labeling on the right.
check more options here.
This example graphs two mathematical functions using plot as the plotting function. The two y-axes enable you to display both sets of data on one graph even though relative values of the data are quite different.
figure
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
[AX,H1,H2] = plotyy(x,y1,x,y2,'plot');
If you are trying with 'hold on' this solves the a-synchronized axes:
set(ax, 'XLim', [min(xaxis) max(xaxis)]);
set(ax(2),'XTick',[]);
The problem is that the background color on the overlayed plot is set to white (and opaqueness to max) so that everything underneath is invisible. Substituting the ax2 = ... statement with
ax2 = axes('Position',get(ax1,'Position'),...
'YAxisLocation','right','XColor','k','YColor','k','color','none');
should fix things.