MATLAB Answers

# How to plot a line graph (x,y) with a color bar representing z-axis...

16 views (last 30 days)
aa on 18 Sep 2020
Edited: Rik on 21 Sep 2020
I have data in multiple y and z axis...
x-axis is fixed while y-axis is varying with eah value of x and z is fixed for each (x,y) pair .... as shown in below figure ...
for example red colour show the fixed value of z-axis (color bar) ... and y is vary w.r.t x.. same is the case for other ..
Both data nd required plot is shown here ...

#### 0 Comments

Sign in to comment.

### Accepted Answer

Rik on 18 Sep 2020
Edited: Rik on 21 Sep 2020
You can use plot, colorbar, colormap, and caxis. You can adjust the line color by setting the Color property of the line object returned by plot.
If you have trouble implementing this, feel free to post a comment about which step exactly is causing you issues, and what you tried to solve it.
The code below was tested on R2011a as well, so it should work for R2013a. Next time, please mention all warnings or errors that you're getting, but most importantly: mention your release. It is 7.5 years old, which in software is very old.
data=xlsread('Pt_data.xlsx');
x=data(:,1);
y=data(:,2:2:end);
z=data(1,3:2:end);
%set z-axis
upper_z=1e-6;
lower_z=1e-9;
%create the colorbar, retrieve the colomap data, and let it match your example image
c=colorbar;
cmap=colormap('jet');
caxis([log10(lower_z) log10(upper_z)])
%set tick positions and create tick labels
Ticks=round(log10(lower_z)):round(log10(upper_z));
TickLabels=arrayfun(@(x) sprintf('10^{%d}',x),Ticks,'UniformOutput',false);
try
set(c,'Ticks',Ticks);
set(c,'TickLabels',TickLabels);
catch %HG1
TickLabels=strrep(strrep(TickLabels,'{',''),'}','');%remove TeX formatting
set(c,'YTick',Ticks);
set(c,'YTickLabel',TickLabels);
end
%normalize the z values to the color scale
z_scaled=(z-lower_z)./(upper_z-lower_z);
z_scaled(z_scaled<0)=0;z_scaled(z_scaled>1)=1;
z_scaled=round(1+z_scaled*(size(cmap,1)-1));%round to nearest index
%plot and select colors from colormap
hold on
for n=1:size(y,2)
C=cmap(z_scaled(n),:);
plot(x,y(:,n),'Color',C);
end
hold off

#### 12 Comments

Show 9 older comments
Rik on 20 Sep 2020
When you post a comment, you will see a bar with editing tools. Please use it to format your code as code. See this page. You will see a button to edit your comment.
As far as your code itself: you shouldn't use clear all. Use clear or clearvars instead. I will also probably only be able to modify the code for R2013a tomorrow.
aa on 20 Sep 2020
Sure ,,, whenever possible for you ... thank
Rik on 20 Sep 2020
You can already edit your comment in the mean time.

Sign in to comment.

R2013a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!