Different right and left axes in a MATLAB plot? - matlab

I plot a single trace in MATLAB with plot(). I'd like to add a right-y axis with a different set of tick marks (scaled linearly). Is this possible?

There are a number of good suggestions on this closely related question, although they deal with a more complicated situation than yours. If you want a super-simple DIY solution, you can try this:
plot(rand(1, 10)); % Plot some random data
ylabel(gca, 'scale 1'); % Add a label to the left y axis
set(gca, 'Box', 'off'); % Turn off the box surrounding the whole axes
axesPosition = get(gca, 'Position'); % Get the current axes position
hNewAxes = axes('Position', axesPosition, ... % Place a new axes on top...
'Color', 'none', ... % ... with no background color
'YLim', [0 10], ... % ... and a different scale
'YAxisLocation', 'right', ... % ... located on the right
'XTick', [], ... % ... with no x tick marks
'Box', 'off'); % ... and no surrounding box
ylabel(hNewAxes, 'scale 2'); % Add a label to the right y axis
And here's what you should get:

You may try this submission to MATLAB File Exchange - PLOT2AXES.
PLOT2AXES example http://www.mathworks.com/matlabcentral/fx_files/7426/2/plot2axes.png

Jiro's solution is good (file Exchange function), however, it does not allow to use Matlab's built-in plot functions (bar, scatter, etc.), and you have to use plot2axes instead. Matlab's own help gives the solution to have two axes on any type of plots:
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','top',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k','YColor','k');
Look at: http://www.mathworks.com/help/techdoc/creating_plots/f1-11215.html

From matlab 2016 and onwards there is an option to define on what axis one plots:
yyaxis left
plots...
yyaxis right
plots...
source:
https://se.mathworks.com/help/matlab/ref/yyaxis.html

Open MATLAB Help with F1 and take a look at the functions below function plot which you mentioned, there you will see plotyy. This is what you probably need.
UPDATE: actually plotyy is NOT the answer to the question as pointed by gnovice.

I was able to do it with the following after plotting the left axis graph:
yyaxis right
ylabel('Right axis label')
plot(x,y1) % plot your right axis graph
Hope it helps.

Related

Plotting in GUI of Matlab

Until now i had only 1 axis in my GUI to I used to just plot directly using plot command. Plus i need to plot these in a loop.
for i = 1:length(sig)
plot(sig(i).time,sig(i).signal,sig(i).time,updated(i).filter,)
hold on
end
Now i have 2 axes in my GUI, how can I make a certain plot appear in 1st axis and another in my 2nd axis
Now for example i need to plot the below in the 2nd axis
for i = 1:length(sig)
plot(sig(i).time,sig(i).fil,sig(i).time,updated(i).sig,)
hold on
end
Any help will be appriciated
You could specify the axes for hold and plot functions. Considering you have two axes, h1 and h2 inside your figure, you could do the following:
hold(h1, 'on')
hold(h2, 'on')
for i = 1:length(sig)
plot(h1, sig(i).time,sig(i).signal,sig(i).time,updated(i).filter)
plot(h2, sig(i).time,sig(i).fil,sig(i).time,updated(i).sig)
end

Matlab: 2 non-continuous colorbars and colormaps in the same figure

I'm completely stranded!!!
Could anyone give me a hand with this issue? Thanks in advance.
What I wanted: I want to plot a brain network such that nodes have their own colormap (jet) and colorbar and, in the same figure, the links with their own colormap (gray) and colorbar.
Problem: When I display on screen the head with two colorbars from two different colormaps, both colorbars display with the first declared colormap (jet) in my code. In other words, it seems that the first declared colormap (jet) re-writes the last declared colormaps (gray). The figure displayed shows the first colormap (jet) and never shows an independent colorbar gray!!!
What have I done?: I had follow so many links through these forums and mathworks helps to build my own script. I'm naive in Matlab and I using it in macOS with matlab version R2013a. The code looks like this:
Figure
hold
plot1 with data1 associated to colormap(gray)
plot2 with data2 associated to colormap(jet)
axis square
axis off
box off
set(gca,'XTick',[],'YTick',[])
set(gcf, 'units','normalized','outerposition',[0 0 1 1]) %EXPANDING FIGURE ON SCREEN
ax1 = gca; %GETTING THE AXES OF THE FORMER FIGURE
ax1p = get(ax1,'Position');
colormap(ax1,'jet') %colorbar for nodes
cb1 = colorbar('west');
set(cb1, 'Position', [ax1p(1)+ax1p(3)-0.17 ax1p(2)+0.17 0.03 ax1p(2)+ax1p(3)-.3])
set(cb1, 'fontsize', 30);
caxis([min(n_atribut) max(n_atribut)]);
ax2 = axes; %getting axes for second colorbar
set(ax2, 'Position', ax1p); % Co-locate ax2 atop ax1
ax2p = get(ax2, 'Position');
axis off; % Make ax2 invisible
linkaxes([ax1,ax2],'xy'); % Link ax1 and ax2 so zooming will work properly:
colormap(ax2,'gray') %colorbar for links
cb2 = colorbar('west'); % Create a new colorbar
set(cb2, 'Position', [ax2p(1)+ax2p(2)+0.6 ax2p(2)+0.17 0.03 ax2p(2)+ax2p(3)-.3])
set(cb2, 'fontsize', 30);
caxis([min(w_atribut) max(w_atribut)]);
axes(ax2);
hold off
Figures. The figure bellow shows the problem and it is what I get when I run my code
As you can see, even when both colorbars have their proper limits associated to data1 and data2, the second (the one to the extreme right) is plotted with colormap jet.
This next figure shows what I looking for:
Obviously, this one was edited in other software to get the colormap gray of the second colorbar.
Having said so, Can anyone could help me please? If it is important I could send the complete code and the 4 files to run and get the wrong figure!
Thanks in advance guys I appreciate all your helps.
Gohann.
You are probably looking for the freezecolor function.
Finally I got my answer due to the comment of Ratbert and the works of so-many guys from MatlabĀ® file exchange. Thankful for the scripts freezeColors.m and cbfreeze.m and double2rgb.m by John Inversen and David Legland Carlos Adrian vargas.
This how I resolved the problem.
% % % % NODOS
cm1 = colormap(jet);
cb1 = colorbar('Location', 'east', 'fontsize', 30);
caxis([min(n_atribut(n_atribut>0)) max(n_atribut)])
cbfreeze(cm1)
freezeColors(ax1)
% % % % LINKS
cm2 = colormap(bone);
cm2 = flipud(cm2);
colormap(cm2);
cb2 = colorbar('Location', 'west', 'fontsize', 30);
caxis([min(w_atribut) max(w_atribut)])
cbfreeze(cm2)
freezeColors
The function/toolKit Easy Plot EEG Brain Network is now available in GitHub and Matlab Fileexchange.
Matlab# FileExchange
GitHub Reposiroty
Thanks to everyone.

Multiple axis: using plot vs. line

I have 2 sets of data I want to plot on the same graph.
First an histogram:
hist(data1);
ax1 = gca;
I set the next set of axis, y on the other side
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k');
If I use line() to plot my data it works:
line(data2a, data2b, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2);
But if I use plot(), the histogram is erased and both axis appear on the left.
plot(ax2, data2a, data2b);
Can somebody figure out why the second axis is not valid for plot()?
You should check out doc hold.
Axes in MATLAB have the 'NextPlot' property, specifying what to do when a new plot-function is issued on this axis.
The default for 'nextplot' is replace, meaning that before anything new is drawn, existing plots are erased.
Using hold(ax, 'on') or set(ax, 'nextplot', 'add') you can specify that new plots are added to the existing ones, instead of replacing them.
The reason that line and plot behave differently is, that high level functions (like plot) respect this axis property, while low-level functions like line, patch and others do not. They are added to axis in any case and do not remove existing children.
EDIT:
Now I'm noticing that ax2 should be empty in your case - maybe just try the above nevertheless ;)

Plot overrides axes property 'XTick'

I am creating a GUI in Matlab. I have several axes in which I plot different graphs. I have set in some of the axes the property XTick to []. However, each time I plot a new graph in the same axes, the xticks appear again. I know I can delete them by using set:
set(handles.axes_0, 'XTick', []);
However, this creates a "flickering" effect: you see the ticks appearing and then dissapearing each time I plot something new.
Do you know how could I have an axes with the XTick disabled avoiding the flickering effect?
Some basic code:
figure(1); %create new figure
set(gca, 'XTick', []); %Disable xtick
plot([1 2 ], [2, 3]); %Plot something. Xtick appears again
set(gca, 'XTick', []); %Disable xtick until next plot
As Shai pointed out in a comment, when using hold on the ticks don't reappear. As I want to clean the previous plot before drawing the new one, I search for its identifier using findobj and then delete it. Finally, I draw the new plot with hold on. Example (suppose the axes handle is called handles.axes_0):
h = findobj(handles.axes_0,'Type','line');
if ~isempty(h)
delete(h);
end
hold on
plot(handles.axes_0,x,y);
hold off

How to make 1-D plots in MATLAB?

How can I make plots in MATLAB like in below?
I won't need labels, so you can ignore them. I tried using normal 2D plot, by giving 0 to y parameter for each data points. It does help, but most of the plot remains empty/white and I don't want that.
How can I solve this problem?
Edit:
This is how I plot(playing with values of ylim does not help):
hold on
for i=1:120
if genders(v_labels(i)) == CLASS_WOMAN
plot(v_images_lda(i,:) * w_lda,0,'r*');
else
plot(v_images_lda(i,:) * w_lda,0,'b.');
end
end
title('LDA 1D Plot');
ylim([-0.2 0.2]);
hold off
One way to do this would be to adjust the 'XLim', 'YLim', and 'DataAspectRatio' properties of the axes so that it renders as essentially a single line. Here's an example:
data1 = rand(1,20)./2; %# Sample data set 1
data2 = 0.3+rand(1,20)./2; %# Sample data set 2
hAxes = axes('NextPlot','add',... %# Add subsequent plots to the axes,
'DataAspectRatio',[1 1 1],... %# match the scaling of each axis,
'XLim',[0 1],... %# set the x axis limit,
'YLim',[0 eps],... %# set the y axis limit (tiny!),
'Color','none'); %# and don't use a background color
plot(data1,0,'r*','MarkerSize',10); %# Plot data set 1
plot(data2,0,'b.','MarkerSize',10); %# Plot data set 2
And you will get the following plot:
Here's one way to reproduce your figure using dsxy2figxy and annotate. dsxy2figxy can be hard to find the first time, as it is not really in your path. It is part of the MATLAB package and is provided in the example functions. You can reach it by searching for it in the help docs and once you find it, open it and save it to a folder in your path.
h1=figure(1);clf
subplot(4,1,1);
hold on
xlim([0.2,1]);ylim([-1,1])
%arrow
[arrowX,arrowY]=dsxy2figxy([0.2,1],[0,0]);
annotation('arrow',arrowX,arrowY)
%crosses
x=[0.3,0.4,0.6,0.7,0.75];
plot(x,0,'kx','markersize',10)
%pipes
p=[0.5,0.65];
text(p,[0,0],'$$\vert$$','interpreter','latex')
%text
text([0.25,0.5,0.65],[1,-1,-1]/2,{'$$d_i$$','E[d]','$$\theta$$'},'interpreter','latex')
axis off
print('-depsc','arrowFigure')
This will produce the following figure:
This is sort of a hackish way to do it, as I've tricked MATLAB into printing just one subplot. All rasterized formats (jpeg, png, etc) will not give you the same result, as they'll all print the entire figure including where the non-declared subplots should've been. So to get this effect, it has to be an eps, and it works with it because eps uses much tighter bounding boxes... so all the meaningless whitespace is trimmed. You can then convert this to any other format you want.
Ok so the closest I have come to solving this is the following
hax = gca();
hold on
for i=1:120
if genders(v_labels(i)) == CLASS_WOMAN
plot(v_images_lda(i,:) * w_lda,0,'r*');
else
plot(v_images_lda(i,:) * w_lda,0,'b.');
end
end
set(hax, 'visible', 'off');
hax2 = axes();
set(hax2, 'color', 'none', 'ytick', [], 'ycolor', get(gcf, 'color');
pos = get(hax, 'position');
set(hax2, 'position', [pos(1), pos(2)+0.5*pos(4), pos(3), 0.5*pos(4)]);
title('LDA 1D Plot');
hold off
So in short, I hid the original axis and created a new one located at 0 of the original axis, and as I couldn't remove the y axis completely I set it's color to the background color of the figure.
You can then decide if you also want to play with the tick marks of the x-axis.
Hope this helps!
Very naive trick but a useful one.
Plot in 2d using matlab plot function. Then using edit figure properties compress it to whichever axis you need a 1D plot on !! Hope that helps :)