How to plot multiple (x,y) series on the same axes with Chaco? - enthought

I have several sets of (x,y) data that I'd like to plot as line plots on the same figure. I have no trouble with matplotlib doing this, but I cannot get the same results with Chaco. Code and output are shown below.
My matplotlib-based code looks like this:
for track in tracks:
xw = np.array(track['xw'])
yw = np.array(track['yw'])
plt.plot(xw, yw, 'b-')
if not plt.gca().yaxis_inverted():
plt.gca().invert_yaxis()
My Chaco-based code looks like this:
for track in tracks:
x = np.array(track['xw'])
y = np.array(track['yw'])
plot = create_line_plot((x,y), color='blue', width=1.0)
plot.origin = 'top left'
container.add(plot)
if track == tracks[0]:
add_default_grids(plot)
add_default_axes(plot)
My matplotlib-based output looks like this:
My chaco-based output looks like this:

The problem with my Chaco-based code above was that I was using an OverlayPlotContainer (container). Because of this, each plot (from create_line_plot) was being drawn with its own axes rather than each plot being drawn on the same set of axes. The following works:
pd = ArrayPlotData()
plot = Plot(pd)
for ii, track in enumerate(tracks):
x = np.array(track['xw'])
y = np.array(track['yw'])
x_key = 'x'+str(ii)
y_key = 'y'+str(ii)
pd.set_data(x_key, x)
pd.set_data(y_key, y)
plot.plot((x_key, y_key), color='blue', origin='top left')

Chaco and Matplotlib are not really trying to address the same types of problems. Matplotlib is better for bringing up a quick plot in a script and is very easy to use. Chaco is a plotting framework that allows:
a stronger architecture for dealing with larger datasets more smoothly
a frameworks that makes it easy to build a GUI around the plot (Traits)
the creation of custom interactive tools on top of plots
Leveraging that framework however requires more code, and the recommeded way to build plots in Chaco is to use its Object Oriented syntax. The simplest but realistic Chaco plot would be something like this. It requires an ArrayPlotData to hold the data and a Plot object to create a plotting area and hold different ways to render that data.
You want to have many line plots instead of just one. You can simply add a for loop inside the __init__ method to add every relevant numpy array inside the ArrayPlotData and for each pair of arrays, to call the plot method of the Plot object (but only 1 Plot object is needed). Something similar is done a little further down in the page.
Good luck,

Related

matlab scatter plot time series

I would like to look at two dimensional data in a time-series - the first idea I had was to use a scatter plot, where you can easily explore timepoint-to-timepoint. Is there a function I could use for this? I looked at scatter3 but it can only plot perfectly-cubic data, not as below:
e.g.
data=rand(5,5,3);
scatter3(data(1,:,:),data(:,1,:),data(:,:,1)) %throws an error
thanks
edit: Originally I had something like >this< in mind
scatter3 seems to be for 3D plots, but you say your data is 2D.
For a simple time-series graph you could presumably even just use plot:
figure
nPoints = 25;
dataX = 1:nPoints;
dataY = rand(1,nPoints);
plot(dataX,dataY, 'o-')
However, the example you give in your link looks like something else, so it seems like scatter (rather than scatter3) might be what you're after. Maybe something like this?
figure
nPoints = 25;
dataX = 1:nPoints;
dataY = rand(1,nPoints);
dataArea = rand(1,nPoints)*100;
dataColours = rand(nPoints,3);
scatter(dataX,dataY,dataArea,dataColours)
EDIT:
I think I understand better what you mean, sorry I didn't see the buttons at the bottom of the link, but correct me if I'm wrong. So you have a set of XY coordinates for multiple objects at different points in time, and ideally you want to plot how the XY coordinates of each object (in 2 dimensions) change over time (in 3 dimensions). Your initial approach in using scatter3 was to try and make a simple 3d graph, but maybe ideally you want a 2d graph that can be either animated or interactive, to change the time point displayed at any given time?
Going back to your original question, I think the issue with your attempt to use scatter3 (or plot3 might be useful too) is I'm not sure what your dummy data would represent. You created data as a 5x5x3 matrix, and I assume that might represent 25 data points, at 3 different time intervals? However, which data would represent the X and which the Y coordinates? It would work with something like the following, where each variable represents the X/Y/Z coordinates of 6 objects (columns) at 5 different time points (rows)
myX = rand(5,6,1);
myY = rand(5,6,1);
% I'm making each time point increase linearly.
myZ = repmat((1:size(myX,1))', 1, size(myX,2));
plot3(myX, myY, myZ, 'o-')
grid on
% Note I find the default dimensions it treats as X, Y and Z unintuitive (e.g. the Z dimension is the vertical dimension), but one could swap the input arguments around to overcome this.
However, especially if you have a lot of points, I'm not sure how clear a graph like this will be, especially compared to the example in your link.
Instead it seems like you ideally want only the XY coordinates of all objects to be plotted for only one time point at once, and a way to cycle through each time point sequentially. This seems trickier, and maybe someone else will be able to answer better than I have. A couple more questions though that might be useful:
How much do you care about the smoothness of the transition. In the example link the circles move smoothly from one position to another, rather than just jumping/teleporting between points.
Ideally do you want a function that would produce an 'animation', cycling through all the time points from begining to end, or a way of manually specifying/changing which time point is being displayed. If the former, maybe this function would be useful (though I've tried it myself yet) https://uk.mathworks.com/matlabcentral/fileexchange/42305-multicomet

Graph different 2D ellipses in 3D axes at different heights in MATLAB

I want to graph different ellipses at different heights (z-coordinates).
My idea was to write the following code:
z=0:1/64:3/8;
t=linspace(-pi,pi,25);
[t,z]=meshgrid(t,z);
x=cos(-t);
y=cos(-t-4*pi*z);
I would like MATLAB to read my code like:
"Find x and y, and plot at the corresponding height (z). By doing so, join the points such that you'll form an ellipse at constant z".
I'm not sure what kind of function I could use here to do this and was hoping for someone to tell me if there exists such a function that will do the job or something similar.
In case you're wondering, I want to graph the polarization of light given two counterpropagating beams.
EDIT: While this is similar to the question draw ellipse and ellipsoid in MATLAB, that question doesn't address plotting 2D ellipses in 3D axes, which is what I am trying to do.
This can be solved by removing the meshgrid, and just using a plain old for-loop.
t = linspace(-pi,pi,25);
z = 0:1/64:3/8
f = figure;
hold on;
for i = 1:length(z)
x=cos(-t); y=cos(-t-4*pi*z(i));
plot3(x,y,z(i)*ones(length(z),1));
end
The problem in the original code is that you're trying build the ellipses all at once, but each ellipse only depends on a single z value, not the entire array of z values.
When I run this code, it produces the following plot:

Smooth Excel-like plot with correct legend in Matlab

I have some sparse data and want to plot them as markers connected by a smooth, interpolated line - like the default behaviour of Microsoft Excel.
There are solutions to this problem easily found on the internet, but I find them unsatisfactory. What they do is: plot the sparse data as one data set drawing it as markers without lines, interpolate it with a method of choice and plot the interpolation as the second data set, with lines without markers.
The problem with these tricks is that in the legend the two data sets will be listed separately. I would expect a single data set depicted in the legend as a line crossing through a marker.
Is it possible in Matlab?
If you want to plot an interpolated line there are lots of ways to do that. You can try generating an interpolated line using the matlab interp1() function.
Let's create x and y data with no NaN.
x = randn(1,10)
y = randn(1,10)
If you want 1000 data points where previously you only had a few, that's pretty easy:
x2 = min(x):(max(x)-min(x))/1000:max(x)
y2 = interp1(x,y,x2,'cubic')
and you can plot your data and spline using
plot(x,y,'r+')
hold on
plot(x2,y2,'r-')
A custom legend is straightforward when you use handle graphics. You can plot a dummy data set with a red line passing through a marker using
h(1) = plot(NaN,NaN,'r-+')
lstring{1} = 'Data';
You can then add a legend that points to this data set using
legend(h,lstring)
You'll end up with something that looks roughly like this:
The nice thing about using handle graphics (i.e. the h) is you can throw whatever data series you want into the legend as h(end+1) and lstring{end+1}.

MATLAB: Interactive tool to "draw" a Plot?

Do you know a simple way to draw arbitrary splines or lines in a plot-figure? I've got the following figure which I created in powerpoint with more or less arbitrary spline-curve (blue) but I'd like to do the same in MATLAB now because of a better look in the final plot-output.
I'm now wondering if I've got to manually "find" data-values to draw some sort of spline (which looks roughly like the blue one below) myself or if there's maybe a tool where I can simply insert some points into a plot interactively and there's a curve fitted though it to create something similar!?
The green and red lines I can figure out myself (probably also have to plot them manually, do I)?!?
Thanks in advance!
EDIT
Okay I found a way myself doing it in MATLAB to gnerate a nice spline: Use splinetool, then either use an example or import some data and then you can interactively add and delete points until your spline looks roughly like it should. Then file->print to figure and then tools->edit plot! You can then delete everything you don't need, add title, xlabel and ylabel etc. and then export it to latex with e.g. matlab2tikz :-) Very nice stuff!!
According the purpose, print nice plots for the thesis, I have some out-of-Matlab recommendations.
1) plot everything as usual, you get a figure handle and an axes handle
h = figure( ... )
a = gca
2) use the data cursor function of the figure window and interactively insert the base points for your later splines. You can additional points by right-click.
t = linspace(0,2*pi,1000);
[x y] = deal(sin(t),cos(t))
Later you delete the "visual" part of the data tip inside Illustrator/Inkscape, if you just want to keep the anchor point of the vector graphic to snap your splines.
There is also the possibility of custom data tips: Tutorial at Matlab Central
3) I once wrote a function to nicely plot Matlab figures as vector graphic based PDFs. You can specify height, width and how much white margin around you want. You just need to pass figure and axes handle and the name:
function saveFigure( fig_handle, axes_handle, name , height , width , margin)
set(axes_handle,'LooseInset',get(gca,'TightInset'));
set(fig_handle, 'Units','centimeters','PaperUnits','centimeters')
% the last two parameters of 'Position' define the figure size
set(fig_handle,'Position',[-margin -margin width height],...
'PaperPosition',[0 0 width+margin height+margin],...
'PaperSize',[width+margin height+margin],...
'PaperPositionMode','auto',...
'InvertHardcopy', 'on',...
'Renderer','painters'... %recommended if there are no alphamaps
);
saveas(fig_handle,name,'pdf')
end
4) You get a PDF you could directly use for Latex - for use in MS Office use 'emf' (
Enhanced metafile) rather than 'pdf'. Open this file with Adobe Illustrator (preferable as it offers layers) or Inkskape (Open Source).
5) The datatips are recognized as graphical objects, you can catch them and draw a spline on them. For Illustrator I'd recommend to put the spline in another layer than the actual figure. Later you can just swap the figure and give the spline new anchor points. In Inkscape you could use the grouping function to keep everything together.
6) I'd say you save a lot of time over a only-Matlab-solution. Good look!

Highlight parts of matlab plot

I have a matlab plot that looks like this:
Where the Y values for each of the subplots are stored in single dimensional arrays. What i would like to do is to find an area where the top graph is above a certain height say 0.5. I would also like to highlight the same area in the other graphs as well.
Here is an example of what I am talking about:
The best i have been able to find so far is the function area which will fill an area on the matlab grid. However, if someone could tell me how to make it transparent and also how to fill multiple areas without having to do lots of area commands that would be great.
Otherwise I can identify a group of areas in a struct and use a for loop to plot them. Here is some psuedo code of the way i would do it:
countstruct = 1;
for i = 1:length(yValue)
if (yValue(i) > 1)
outside = [outside, i]
else
areas(countstruct).outside = outside;
countstruct = countstruct + 1;
clear outside;
end
end
Then to plot the areas i would do this:
for i = 1:length(areas)
area(areas(i).outside, ones(length(area), 1)*14, "SomeThingToMakeItTransperant')
end
and i would do this for each of the subplots. Obviously this is quite convoluted so it would be better to have a one liner. Can anyone think of one?
I figured it out, The psuedo code i provided gets the correct regions. You can then do this:
for i = 1:length(areas)
harea = area(areas(i).outside, ones(length(areas(i).outside), 1)*14, 'LineStyle', 'none')
set(harea, 'FaceColor', 'r')
alpha(0.25)
hold on
end
alpha sets the transparency in most area plots. This in combination with the code in the question results in this:
This is pretty cool to plot in matlab.