Matlab, gplot custom linewidth for some lines, but not all - matlab

In the past, there has been asked a question about customizing the linewidth in gplot (see In MatLab, how to adjust the line width drawn by the function 'gplot'?). I am dealing with a slightly more complicated version, which prevents me from using the solution given there. Therefore, I would like to ask how to do the following: I would like to adapt the line width of some of the calls of gplot, and not of others. I am namely calling gplot several times and using hold on to plot them in one figure. I am trying to draw a graph, with multiple types of edges (A and A2). And k paths in it. I am currently using the following code:
figure
hold on
gplot(A,coor,'k*:')
gplot(A2,coor,'k-')
plot(coor(T,1),coor(T,2),'k.','MarkerSize',20)
plot(coor(T,1),coor(T,2),'bo','MarkerSize',20)
% a line where I define my own colors (not shown, since not relevant)
set(gca,'ColorOrder',colors)
hold all
for i=1:k
gplot(Path,coor)
end
hold off
But I would like to draw the paths with a larger line width, while keeping the A and A2 at the standard line width 1.
Can someone help me? Thank you very much!

You can get the children of the axis before and after adding the extra lines, and only set the new ones to have a larger linewidth:
figure
hold on
gplot(A,coor,'k*:')
gplot(A2,coor,'k-')
plot(coor(T,1),coor(T,2),'k.','MarkerSize',20)
plot(coor(T,1),coor(T,2),'bo','MarkerSize',20)
ChildrenBefore=get(gca,'children');
% a line where I define my own colors (not shown, since not relevant)
set(gca,'ColorOrder',colors)
hold all
for i=1:k
gplot(Path,coor)
end
hold off
ChildrenAfter=get(gca,'children');
NewChildren=setdiff(ChildrenAfter,ChildrenBefore);
set(intersect(findall(gcf,'type','line'),NewChildren),'LineWidth',5)

Related

Triangular split patches with painters renderer in MATLAB 2014b and above

MATLABs new graphics engine, HG2, fails to properly print patches using the painters renderer:
hist(randn(1,1000));
colorbar('Location','SouthOutside');
print('test.pdf','-dpdf');
The resulting patches, whether generated by hist or colorbar, have triangular splits:
The issue has been discussed on MATLAB Central here and here, where it was suggested that disabling the "smooth line art" option in the pdf-viewer should solve it. This conceals the problem in some readers (e.g. in Adobe Reader but not in Apple Preview), but it is hardly a solution to ask collaborators and readers to use a specific pdf-viewer with non-default settings for graphics to appear correctly. Looking at the resulting file in Inkscape, it is clear that the split is present in the output vector graphics. Here, I moved one half of the colorbar, proving that it is in fact split in half, and not just misinterpreted by the pdf-viewer:
The problem is not present using the OpenGL renderer (print('test.pdf','-opengl'), but then the output is not vectorized). The problem persists in MATLAB 2015a.
Is there a way to export artifact-free vector graphics in MATLAB 2014b or later?
Here's a questionable work-around until the actual problem is solved:
The diagonal lines are simply the empty space between the triangles, so what we are seeing is the white space behind the patches peek through. Silly idea:
Let's fill that space with matching colors instead of white.
To do so, we'll copy all objects and offset the new ones by just a tiiiiny bit.
Code:
hist(randn(1,1000));
colorbar('Location','SouthOutside');
print('test.pdf','-dpdf'); %// print original for comparison
f1 = gcf;
g = get(f1,'children');
n = length(g);
copyobj(g,f1); %// copy all figure children
The copied objects are now the first n elements in the 2*n f1.Children array. They are exactly on top of the old objects.
g=get(f1,'children');
for i=1:n;
if strcmpi(g(i).Type,'axes');
set(g(i),'color','none','position',g(i).Position+[0.0001 0 0 0]);
set(g(i+n),'position',g(i+n).Position); %// important!
end;
end;
print('test2.pdf','-dpdf');
Explanation:
g = get(f1,'children'); gets all axes, colorbars, etc., within the current figure.
colorbar objects are linked to an axes, which is why we'll only have to move the axes type children.
Setting the color to none makes the background of the new axes transparent (since they are on top of the old ones).
g(i).Position+[0.0001 0 0 0] shifts the new axes by 0.0001 normalized units to the right.
set(g(i+n),'position',g(i+n).Position); This line seems unnecessary, but the last image below shows what happens when printing if you don't include it.
Depending on the types of graphics objects you have plotted, you may need to tweak this to fit your own needs, but this code should work if you have only colorbar and axes objects.
Original:
With hack:
Without %// important! line:
In R2015b, histogram seemed to not show the white lines, but fill did.
For simple plots just paste the data again:
x = 0:pi/100:pi;
y = sin(x);
f = fill(x,y,'r');
hold on;
f2 = fill(x,y,'r'); %// Worked like magic
If the magic fails try similar to Geoff's answer: f2 = fill(x+0.0001,y,'r');
Depending on what version of Matlab you are using, you might try to use epsclean. It doesn’t seem to work with very recent versions of Matlab like 2017a.
Otherwise, epsclean can be run on an existing eps file (not pdf) exported with the -painters option to generate a vectorized figure, and it will rewrite (or create another file) with those white lines removed.

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!

making axes distinct from other grid

Does anyone know how to make x-axis and y-axis look a bit bolder or somehow distinct from other grids?
Somehow I want it to look like this
The stupidest thing I can think of is drawing a line with LineWidth = 2
figure();
plot([0 0],[-200 200],'LineWidth',2,'Color',[0 0 0])
hold on;plot([-200 200],[0 0],'LineWidth',2,'Color',[0 0 0])
Though it has some obvious disadvantages, like that it ends at some place.
Check out hline and vline from the MATLAB File Exchange. It will let you draw horizontal and vertical lines at any given point and extend those lines to infinity (so redoing axes will still keep the lines drawn all the away across your plot). If you need to draw to specific handles, here's an advanced hline/vline.

How to vary the line color of a matlab plot (like colormap)?

I have a 2D space in which a function value is defined (you can think of it as a manifold). Now I plotted the function value using contourf and changed the colormap to something softer than jet. So far it looks quite good.
Now I want to draw a line representing the state over time in my space. That is also possible using the the plot command. But I want some more improvements: There is an additional state that is hidden for now (value 0...50). I would like the line color to change according to this hidden state. So in a sense to apply a separate colormap to the line plotted by plot like for example in a waterfall plot.
Is this (or something similar) possible using matlab?
Thanks
If you want to either use interpolated shading or have the colours change with the colour map, then you want to plot your data as a mesh and set the edgecolor property appropriately. Note that in order to plot it as a mesh, then you will need to duplicate it so that it has a size of at least 2 in each direction.
h = mesh([X(:) X(:)], [Y(:) Y(:)], [Z(:) Z(:)], [C(:) C(:)], ...
'EdgeColor', 'interp', 'FaceColor', 'none');
You may also want to look at the MeshStyle property, if you want to plot multiple lines simultaneously.
This solution is also much nicer than the one used in cline because it only creates one graphics object, rather than n.
Have a look into the cline.m function from file exchange, I think it is exactly what you need.
I can recommend the Colored line entry from the file exchange. It has good feedback and uses the color map to define the displayed colours, I've use it sucessfully on a number of projects.

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.