Plotting hidden variable/parameter - matlab

I would like to plot some parametric plots as a function of a 0-1 variable.
I can easily set up x=linspace(0,1) and define functions a(x), b(x), and plot(a,b).
What I would like to do, however, is indicated in the plotted diagrams the value of my original x parameter. I would guess there is a function to do so, although I haven't found it yet. Optionally, I could also do a color gradient with a bar along each trace for my 0-1. Can anyone point me in the right direction?

Good news! You can do all sort of things quite easily, let's start with defining some data:
x = linspace(0,1);
a = sin(5.*x);
b = cos(6.*x);
Now, we make a simple plot:
plot(x,a,'-o',x,b,'^')
The '-o' means the first series of data (a) will be plotted as line with circle markers, the '^' means the second series of data (b) will be plotted with no line, just triangles. You can find all options here.
Next, we call:
text(x(50)+0.03,a(50),sprintf('x = %0.3f',x(50)),'FontSize',14)
text(x(30)+0.03,b(30),sprintf('x = %0.3f',x(30)),'FontSize',14)
the text command print text at specific coordinates on the figure. For example, the first line will print in (x(30)+0.03,a(30)) the text "x = 0.495". The text string is formatted with another function sprintf, but you can just write simple text in single quote marks (').
Finally, we can add legend by:
legend({'sin(5x)','cos(6x)'},'FontSize',16,'Location','SouthWest')
note that the text strings are in a cell array.
And we get the result:
That's the kind of stuff you have been looking for?

Related

How do I pass an array of line specifications or styles to plot?

I want to plot multiple lines with one call to plot(), with different line styles for each line. Here's an example:
Both
plot([1,2,3]', [4,5;6,7;8,9], {'-o', '-x'})
and
hs = plot([1,2,3]', [4,5;6,7;8,9])
set(hs, 'LineStyle', {'--'; '-'})
don't work. I've tried a whole bunch of arcane combinations with square and curly braces, but nothing seems to do the trick.
I know it's possible to loop through the columns in Y and call plot() for each one (like in this question), but that isn't what I'm after. I would really like to avoid using a loop here if possible.
Thanks.
PS: I found this 'prettyPlot' script which says it can do something like this, but I want to know if there's any built-in way of doing this.
PPS: For anyone who wants a quick solution to this, try this:
for i = 1:length(hs)
set(hs(i), 'Marker', markers{i});
set(hs(i), 'LineStyle', linestyles{i});
end
e.g. with markers = {'+','o','*','.','x','s','d','^','v','>','<','p','h'}
Referring to http://www.mathworks.com/help/matlab/ref/plot.html, this is how to draw multiple lines with a single plot command:
plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)
So your idea of
plot([1,2,3]', [4,5;6,7;8,9], {'-o', '-x'})
must be written as:
plot([1,2,3]', [4,6,8], '-o', [1,2,3]',[5,7,9],'-x')
resulting:
Reorganize input parameters into cell arrays and use cellfun to apply plot command to each cell element.
x = [1,2,3]';
xdata = {x;x};
ydata = {[4,6,8];[5,7,9]};
lspec = {'-o';'-x'};
hold all;
cellfun(#plot,xdata,ydata,lspec);

How do I place the Date and Time on my horizontal axis to be in separate rows in a figure in MATLAB?

I am plotting a graph of random data versus datetime strings. These datetime strings are all in one line and serve as labels on the horizontal axis. I would like the date to be displayed in one line and the time to be in another line.
The image below describes my graph. I would like the time to be displayed underneath the date.
The code I used to generate the graph is shown below:
figure
plot(sample(:,1),sample(:,2:5),'o')
tick=get(gca,'xtick');
set(gca,'xticklabel',datestr(tick,31))
drawnow()
How can I get the time of each horizontal label to appear below the date?
This is a bit of a hack, but you can introduce the TeX command \newline inside the date string in between the spaces of the date and the time, then set these new strings to be the X Tick labels in your figure. You'll need to convert the character array that is output from datestr into a cell array of strings with cellstr, then use strrep to perform the replacement from a space to \newline.
Something like this should work:
figure
plot(sample(:,1),sample(:,2:5),'o')
tick=get(gca,'xtick');
vals = cellstr(datestr(tick,31)); %// Change
new_vals = strrep(vals, ' ', '\newline'); %// New
set(gca,'xticklabel',new_vals); %// Change
drawnow()
When I do this with a sample plot:
plot(1:6, 1:6, 'r.');
I get this as the final result once I run the code:
Take note that this assumes that the X Ticks are sufficiently spaced apart from each other. Your plot will look cluttered if you have many ticks on the horizontal axis.

Matlab: Format the decimals in contour labels

I want to cut the number of decimals in the following contour plot. I do:
[cc,hh] = contour(X,Y,Z,levels,'LineColor','k');hold on
texth = clabel(cc,hh,'FontSize',8);
which gets me the first contour with long labels. Then in order to cut the decimals I do:
for i = 1:size(texth); textstr=get(texth(i),'String'); textnum=str2double(textstr); textstrnew=sprintf('%0.0f', textnum) ; set(texth(i),'String',textstrnew); end
And this gives the second plot. As you see, there is a wide gap between the label and the contour lines which looks awful. Any ideas how to solve this?
Instead of modifying the result, create a contour plot with the levels you want, so you don't need to cheat the data.
Define levels as e.g. levels=997:1010
and then
contour(X,Y,Z,levels,'LineColor','k','ShowText','on');
Will create a contour plot with the text included and the levels being specifically the ones in the variable levels, in this case 997,998,999,...,1009,1010
If, as #David suggests, your levels variable already is a vector, then replace it by round(levels) as himself suggested.

Use another variable to color-code single quiver arrows

how would one go about to get and use a color-coding from a variable to color a single quiver3 line?
I append a picture where i made a scatter plot in variable z that i would like the blue line emanating from there to be the same color. Is there a possibility?
Thanks.
Not with standard quiver. There's a file available on the File Exchange called quiverc, which uses the magnitude of the vector as the line color.
It's also not too hard to roll your own:
function colQuiver(xyz, uvw, cdata)
%// this makes it suitable for both 2D and 3D
xyz = num2cell(xyz);
uvw = num2cell(uvw);
for ii = 1:size(xyz,1)
L = cellfun(#(x,y) [0;x] + [y;y], ...
uvw(ii,:), xyz(ii,:),...
'Uniformoutput', false);
L = line(L{:});
set(L, 'color', cdata(ii,:));
end
end
Note that I didn't test this at all, there's no error checking, and you might want to allow other ways of specifying the color than just RGB values (use a LineSpec, via current colormap, ...)...But the essence it there ^_^
In case you are wondering for colored arrows:
QuiverS and Uquiver and Streakarrow3d. But none of them does what i want. They all have the arrows the same length and color coded, however i'd rather have them different lengths and color coded with yet another variable.

Plotting multi-colored line in Matlab

I would like to plot a vertical line (I'd prefer any orientation, but I'd be happy with just vertical right now) with two-color dashes, say red-blue-red-blue-...
I know I could do it like this:
plot([1,1],[0,1],'r'),
hold on,
plot([1,1],[0,1],'--b')
However, since I need to be able to move the line, among others, it should only have a single handle. How could I do this?
EDIT
Thank you for your answers. I guess I should indeed give some more information.
I have some data that is classified into different parts. I want to be able to manually adjust the boundaries between classes. For this, I'm drawing vertical lines at the classification boundaries and use draggable to allow moving the lines.
For the boundary between the red and the blue class, I'd like to have a red/blue line.
plot(ones(10,1),linspace(0,1,10),'-bs','MarkerFaceColor','r','MarkerEdgeColor','none','linewidth',6)
is what I'm actually using at the moment. However, it's not so pretty (if I want equal spacing, it becomes a real pain, and I want to give both colors the same weight), and I would like to have the possibility to use three colors (and not with marker edge and face being different, because it makes my eyes bleed).
Unfortunately, draggable does not allow me to use multiple handles, and grouping the lines with hggroup does not seem to create a draggable object.
cline looks like a promising approach, but rainbow colors won't work for my application.
You can use the code you have, and just concatenate the handles from each line into a vector of handles. When you want to change the properties of both lines simultaneously, the SET function is able to accept the vector of handles as an argument. From the documentation for SET:
set(H,'PropertyName',PropertyValue,...)
sets the named properties to the
specified values on the object(s)
identified by H. H can be a vector of
handles, in which case set sets the
properties' values for all the
objects.
Here's an example:
h1 = plot([1 1],[0 1],'r'); %# Plot line 1
hold on;
h2 = plot([1 1],[0 1],'--b'); %# Plot line 2
hVector = [h1 h2]; %# Vector of handles
set(hVector,'XData',[2 3]); %# Shifts the x data points for both lines
UPDATE: Since you mention you are using draggable from the MathWorks File Exchange, here's an alternate solution. From the description of draggable:
A function which is called when the
object is moved can be provided as an
optional argument, so that the
movement triggers further actions.
You could then try the following solution:
Plot your two lines, saving the handle for each (i.e. h1 and h2).
Put the handle for each in the 'UserData' property of the other:
set(h1,'UserData',h2);
set(h2,'UserData',h1);
Create the following function:
function motionFcn(hMoving) %# Currently moving handle is passed in
hOther = get(hMoving,'UserData'); %# Get the other plot handle
set(hOther,'XData',get(hMoving,'XData'),... %# Update the x data
'YData',get(hMoving,'YData')); %# Update the y data
end
Turn on draggable for both lines, using the above function as the one called when either object is moved:
draggable(h1,#motionFcn);
draggable(h2,#motionFcn);
I've never used it, but there's a submission by Sebastian Hölz called CLINE on the Mathworks File Exchange that seems related.
I don't know how to do exactly what you want, but presumably the reason you want to do this is to have some way of distinguishing this line from other lines. Along those lines, take a look at MathWorks' documentation on 2-D line plots. Specifically, this example:
plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)
should give you plenty of ideas for variation. If you really need the two-color dashes, it might help to specify why. That way, even if we can't answer the question, perhaps we can convince you that you don't really need the two-color dashes. Since you've already ruled out the over-lapping solution, I'm fairly certain there's no solution that answers all of your needs. I'm assuming the two-colorness is the most fluid of those needs.