It should have a simple answer which I am missing somehow.
I want to plot only the data points in the x axes. The other points makes things more confusing.
Here is my code:
figure(6);
grid on;
hold on;
colorVec = hsv(length(crl));
for i = 1:(length(crl)-1)
plot(dc,pathLoadMatrix(i,:),'Color',colorVec(i,:),'linewidth',2, 'marker','o');
end
legend('Crl 10%', 'Crl 20%', 'Crl 30%', 'Crl 40%', 'Crl 50%');
xlabel('No of DC');
ylabel('Primary Path Load');
hold off;
Try this: set( gca(), 'xtick', [2:6] )
An answer must be at least 30 characters, so this is filler text.
Related
I want to draw two separated lines, but I get the two lines on two points. How do I draw them separated?
When you implement the code, the green line should start from point 3 and end in point 4 on the x-tick. But, it starts again from point 1 and end in point2.
%% My question code:
a=3; %point1
b=4; %point2
c=6; %point3
d=7; %point4
plot([a b], 'k- *');
hold on;
plot([c d], 'g- *');
hold off
set(gca, 'XTick', 1:4, 'XTickLabel', {'point1', 'point2', 'point3','point4'})
axis([0 10 0 10]);
When you hold the current plot and plot a new one. x axis values are taken as if it is the first plot. To avoid the confusion, specify values for both x and y axes.
So change your plot commands like this:
plot([1,2], [a,b], 'k- *');
hold on;
plot([3,4], [c,d], 'g- *');
hold off;
or combine two plot commands into a single one like this:
plot([1,2], [a,b], 'k- *', [3,4], [c,d], 'g- *');
i have a question regarding legend for movies.
This is my code:
fig = figure();
for i = 1: 70000
plot(signal1)
hold on;
plot([i,i],[-5,5])
plot(signal2,'r')
hold off;
title('\fontsize{14} my data');
legend('signal1','signal2');
axis tight;
f(i) = getframe(fig);
end
The legend shows the same colors for the first two things I plot. if I plot more it works for the other plots. Is there a trick I don't know?
The strings defined in the legend command are assigned in order of the plots being generated. This means that your first string 'signal1' is assigned to the plot for signal1 and the second string 'signal2' is assigned to the vertical line.
You have two possibilities to fix this problem.
Execute plot for the vertical line after the plot for the two signals.
Use handles to the plots to assign the legends directly.
Here is an example of changing the order:
plot(signal1)
hold on;
plot(signal2,'r')
plot([i,i],[-5,5],'k')
hold off;
legend('signal1','signal2');
Here is an example that uses handles (sp1 and sp2):
sp1 = plot(signal1)
hold on;
plot([i,i],[-5,5],'k')
sp2 = plot(signal2,'r')
hold off;
title('\fontsize{14} my data');
legend([sp1,sp2],'signal1','signal2');
I am having trouble matching my graph with my axis. The first two plots work and the second two do not. I am trying to plot Temperature versus Pressure for two Argo floats and then Salinity versus Pressure. Here is my code:
% First Plot
subplot(221);
plot(float1winter.T,float1winter.P,'b');
hold on;
plot(float1summer.T,float1summer.P,'r');
hold on;
tempAdiff = abs(float1summer.T-float1winter.T)
plot(tempAdiff,float1summer.P,'--k');
hold on;
set(gca,'ydir','reverse');
title('Argo Float #1901440 Temp Profiles');
legend(['float1winter','float1summer','tempAdiff'],{'11-29-2013','07-01-2013','Temperature Difference'},'location','southwest');
xlabel('Temperature (°C)');
ylabel('Pressure');
shg;
% Second Plot
subplot(222);
plot(float2winter.S,float2winter.P,'m');
hold on;
plot(float2summer.S,float2summer.P,'c');
hold on;
set(gca,'ydir','reverse');
title('Argo Float #1901440 Salinity Profiles');
legend(['float2winter','float2summer'],{'11-29-2013','06-02-2013'},'location','southwest');
xlabel('Salinity (psu)');
ylabel('Presure');
shg;
% Third Plot
subplot(223);
% Matrix demensions did not agree bewteen winter and summer profiles. The summer profile was 71 x 2 and the winter was 70 x 2. I tried "reshape"
% and that didn't work. So I changed the vector of float3summer.T to
% float3bsummer.T with an array of 70 x 2
float3bsummer.T = float3summer.T(1:70,1:2);
float3bsummer.P = float3summer.P(1:70,1:2);
plot(float3winter.T,float3winter.P,'Linewidth',1,'color','blue');
hold on;
plot(float3bsummer.T,float3bsummer.P,'Linewidth',1,'color','red');
hold on;
tempdiff = abs(float3bsummer.T-float3winter.T)
plot(tempdiff,float3bsummer.P,'--k');
hold on;
set(gca,'ydir','reverse'); % this line reverses the y-axis so that depth increases downward
title('Argo Float #1901415 Tempearture Profiles');
hold on;
summerfloat = plot(float3bsummer.T,float3bsummer.P,'r');
legend(['float3winter.T','summerfloat','tempdiff'],{'12-03-2013','07-03-2013','Temp Diff'},'location','southeast');
xlabel('Temperature (°C)');
ylabel('Pressure');
axis ([-1,4,0,2000]);
shg;
% Fourth Plot
subplot(224);
plot(float3winter.S,float3winter.P,'g');
% Changed matrix dimensions for Salinity of Summer
float3bsummer.S = float3summer.S(1:70,1:2);
float3bsummer.P = float3summer.P(1:70,1:2);
plot(float3bsummer.S,float3bsummer.P,'.b');
hold on;
set(gca,'ydir','reverse');
title('Argo Float #1901415 Salinity Profiles');
h4 = plot(float3winter.S,float3winter.P,'g');
hold on;
h5 = plot(float3bsummer.S,float3bsummer.P,'.b');
hold on;
legend(['float3winter','float3bsummer.T'],{'12-03-2013','07-03-2013'},'location','southwest');
xlabel('Salinity (psu)');
ylabel('Pressure');
axis ([33.8,34.8,0,2000]);
shg;
% Save File to Desktop
set(gcf,'color','w');
saveas(gcf,'~/Desktop/hw1_figure1.pdf','pdf');![enter image description here][1]
I guess that you're trying to associate the set of strings for your legend, {'11-29-2013','07-01-2013','Temperature Difference'}, with the plots made from the variables ['float1winter','float1summer','tempAdiff'].
However, this isn't how legend works. MATLAB has no way of associating the plot produced by plot(float1winter.T,float1winter.P,'b'); to the string float1winter. If you want to specify which plots go with which legend entries, you need to pass the object handles of the plots to legend, which is easiest done by returning the handles when you plot originally:
h(1) = plot(float1winter.T,float1winter.P,'b');
hold on;
h(2) = plot(float1summer.T,float1summer.P,'r');
h(3) = plot(tempAdiff,float1summer.P,'--k');
legend(h,{'11-29-2013','07-01-2013','Temperature Difference'});
Side note: you only need to call hold on once per axis - so once for each subplot but not after every plot call.
Alternatively, you can not give handles at all; legend will assign the text to the plots in the order that they were plotted:
legend({'11-29-2013','07-01-2013','Temperature Difference'})
Understanding graphics handles allows you a lot more control over plots, especially if you might want to make small adjustments to them. For example, if I decide that I want the first plot to be green rather than blue, then I can just do:
set(h(1),'Color','g');
This will change the plot color and the legend changes to match automagically. To see a list of all the properties of an object, use get with only the handle. You can set more than one property at a time. For example:
get(h(1))
set(h(1),'DisplayName','Winter','LineWidth',3,'Marker','x')
I have an RGB image, img, and I want to produce a new image, img2, with an overlay scatter plot on it.
If X Y Z are respectively the nx1 vectors of x-coord, y-coord and "magnitude" value of my scatter what I'm doing is:
imshow(img);
hold on;
scatter(X,Y,3,Z,'fill');
hold off;
In this way I actually get an image with the scatter plotted, but the problem is that every point of the scatter has the same color (blu) instead of what normally happens when I use
figure;
scatter(X,Y,3,Z,'fill');
Any suggestions? Thanks.
Try to add figure; before imshow(), which will enables you to draw on the image with the color that what normally it should be.
figure; % add this line before imshow()
imshow(img);
hold on;
scatter(X,Y,3,Z,'fill');
hold off;
Here is an example I just tested:
figure; % add this line before imshow()
imshow(img);
hold on;
load seamount
s = sqrt(-z/2);
c = z;
scatter(x,y,s,c,'fill')
hold off;
You can see that its color shown on the image is (roughly) consistent with the color when drawing it alone.
Edit: you can always change the color to whatever you like by setting scatter's color properties, i.e. MarkerEdgeColor and MarkerFaceColor.
Ok, remapping the values of Z to 0-255 it works fine. Here is my function to do that:
function [ Aremaped ] = remap( A,lnew,hnew )
Aremaped = zeros(size(A));
lold=min(A);
hold=max(A);
for i=1:length(A)
newVal = lnew + (A(i)-lold)*(hnew-lnew)/(hold-lold);
Aremaped(i) = newVal
end
end
Hope this can help
I want to show only the legend for a group of data in MATLAB.
The reason I want to do this is that I want to export the legend to .eps, but I only want the legend, not the plots.
Is there a way to turn off the plots and remove them from the figure, but still show just the legend centered?
This seems to do the trick:
plot(0,0,'k',0,0,'.r') %make dummy plot with the right linestyle
axis([10,11,10,11]) %move dummy points out of view
legend('black line','red dot')
axis off %hide axis
There is probably a lot of whitespace around the legend. You could try to resize the legend by hand, or save the plot and use some other program to set the bounding box of the eps.
The chosen solution by Marcin doesn't work anymore for R2016b because MATLAB's legend will automatically gray out invisible plots like this:
Neither turning off the automatic update of the legend nor changing the TextColor property afterwards fixes this. To see that, try Marcin's modified example:
clear all; close all;
figHandle = figure;
p1 = plot([1:10], [1:10], '+-');
hold on;
p2 = plot([1:10], [1:10]+2, 'o--');
legHandle = legend('text1', 'text2');
%turn off auto update
set(figHandle,'defaultLegendAutoUpdate','off');
set(p1, 'visible', 'off');
set(p2, 'visible', 'off');
set(gca, 'visible', 'off');
%set legend text color to black
legHandle.TextColor = [0 0 0];
The result remains the same. (To avoid throwing my laptop through the window) and fix this without zooming, which might leave fragments of the plot in the way, I wrote a function that fixes the legend and saves it to a file (with frame):
function saveLegendToImage(figHandle, legHandle, ...
fileName, fileType)
%make all contents in figure invisible
allLineHandles = findall(figHandle, 'type', 'line');
for i = 1:length(allLineHandles)
allLineHandles(i).XData = NaN; %ignore warnings
end
%make axes invisible
axis off
%move legend to lower left corner of figure window
legHandle.Units = 'pixels';
boxLineWidth = legHandle.LineWidth;
%save isn't accurate and would swallow part of the box without factors
legHandle.Position = [6 * boxLineWidth, 6 * boxLineWidth, ...
legHandle.Position(3), legHandle.Position(4)];
legLocPixels = legHandle.Position;
%make figure window fit legend
figHandle.Units = 'pixels';
figHandle.InnerPosition = [1, 1, legLocPixels(3) + 12 * boxLineWidth, ...
legLocPixels(4) + 12 * boxLineWidth];
%save legend
saveas(figHandle, [fileName, '.', fileType], fileType);
end
Tips for use:
fileType is a string that specifies a valid argument for saveas(), such as 'tif'.
Use it after you have plotted everything you want to appear in your legend, but without extra stuff. I'm not sure if all potential elements of a plot contain an XData member that isn't empty.
Add other types of displayed things that you want deleted, but are not of type line if there are any.
The resulting image will contain the legend, its box, and a little bit of space around it the legend is smaller than the minimum width (see Minimum Width of Figures in MATLAB under Windows). However, this is usually not the case.
Here is a complete example using the function from above:
clear all; close all;
fig = figure;
p1 = plot([1:10], [1:10], '+-');
hold on;
p2 = plot([1:10], [1:10]+2, 'o--');
legendHandle = legend('myPrettyGraph', 'evenMoreGraphs');
saveLegendToImage(fig, legendHandle, 'testImage', 'tif');
I think that you need to "hide" the elements you don't want in your plot, leaving out only the legend. For example,
clear all; close all;
figure;
p1 = plot([1:10], [1:10], '+-');
hold on;
p2 = plot([1:10], [1:10]+2, 'o--');
legend('text1', 'text2');
set(p1, 'visible', 'off');
set(p2, 'visible', 'off');
set(gca, 'visible', 'off');