How to print a reversed colorbar in matlab? - matlab

I want to reverse a colorbar on a figure saved as a pdf from Matlab. I can reverse the colorbar on my screen, but when I print my figure as a pdf the colorbar is flipped back to the normal direction again.
Minimum example:
figure(1)
colormap(parula(100))
c = colorbar('direction','reverse');
print(1,'-dpdf','graphs\test_colorbar.pdf',sprintf('-r%d',150))
Using export_fig does not help - when export_fig prints a reversed colorbar it flips the colormap and reverses the label order, which does not work if the ticks are not symmetric around the middle value of the colorbar.
Minimum example showing why flipping the colorbar and labels does not help:
tick_array = 0:0.3:1;
figure(1)
colormap(parula(100))
colorbar('direction','reverse','Ticks',tick_array)
export_fig('graphs\test_colorbar.pdf','-pdf')
tick_labels = strtrim(cellstr(num2str(flip(tick_array)')));
figure(2)
colormap(flipud(parula(100)))
colorbar('Ticks',tick_array,'Ticklabels',tick_labels)
The figure saved by export_fig looks like figure 2 (which is incorrect).

Try reversing the map itself, instead of the parameter that control its direction:
figure(1)
c = parula(100);
colormap(flipud(c));
colorbar;
print(1,'-dpdf','graphs\test_colorbar.pdf',sprintf('-r%d',150))
I also really suggest export_fig for saving images in MATLAB, especially for publication quality figures

Related

How to avoid marker clipping in Matlab while saving two axis figure to pdf?

I have some trouble while exporting a two axis figure with Matlab to pdf. The following example code works great while creating the figure in Matlab. But in the generated pdf-file all my red markers on the x-axis get cut off (see screenshot). Curiously this problem only occures, when I use a two axis plot
Here is a screenshot of my figure
fig = figure;
x = linspace(0,25);
y = sin(x/2);
marker = linspace(0,25,5);
yyaxis left
plot(x,y,'g');
hold on;
r = x.^2/2;
yyaxis right
plot(x,r,'b');
hold on;
plot(marker,0,'rx','Markersize', 8);
saveas(gcf,'myfigure.pdf');
Can anyone please help me out here?
I’ve come into this a handful of times, super frustrating. I’ve usually tried some of the below options, and eventually something works. Some things to try:
Print as a png, then convert to PDF with gimp or something of the like (where 300 represents 300 dpi):
print(handle, savefilename, ‘-dpng’, ‘-r300’)
Print as a vector image with the painters renderer, then convert to PDF with gimp:
print(handle, savefilename, ‘-depsc’, ‘-painters’)
Try changing the marker to a different shape, or size, or both (using for example: 'markersize', 3, 'marker', 's')
Good luck. Let us know what ends up fixing it!

MATLAB: imagesc() and image() display the same colormap differently

I have some data I would like to display in a picture form. In one case I want to rescale the x and y axis, which leads me to using imagesc. The issue is that the same colormap (jet) looks different in imagesc as compared to image.
Is there a way to make them the same?
I am using MATLAB R2014a.
Demonstration:
Here is how I show them:
figure; image(cancelledmap); colormap(jet); %image
figure; imagesc(y,x,cancelledmap); colormap(jet); %imagesc
And the output:
The colormap settings for both figures are somehow the same, however:
imagesc scales the color axis, whereas image does not. That's why the colors look different. If you click the colorbar button you'll see that they are on different color scales.
You can change the colorscale with caxis.
By the way, if you only want to scale the X- and Y-axes, you can use either function. Just supply your own scaled x and y vectors.

Matlab: (1) Plotting multiple canvases, (2) holding them separately, (3) montage all

I've got 10 grayscale images. I'd like to plot a simple YELLOW line over each image separately, then show them all over one plot (montage style).
I tried to draw all images first, but that made plotting lines very tricky (X,Y axes weren't standard for plotting over each separate image).
I thought about burning the line over the image, but I don't have the computer vision toolkit (easy functions to do this), otherwise it seemed complicated to both convert the grayscale to color and get it to burn the image.
I thought I might be able to use the function newplot to create a temporary plot space for each image, draw the line with a simple plot(...) call, then save it and just montage(...) all the individual plots at the end.
Is this possible? I've never played with the function newplot or tried to loop through individual plots, saving them up for a call to montage(...) this way, but it seems like a logical/simple approach.
I finally worked it out with subplot, subimage, and plot, using subplot with the position arguments does what I want easily enough. Using subplot kept the axis relative to the subplot I was on so I could plot the line with a standard fplot/plot call. The trick was normalizing the position to percentages vs. thinking of it in terms of pixels.
here's some code demoing it:
% Loop through this code, each time moving the subplot by position
LOOP {
% calculate left & bottom position as percentages (0..1)
subplot( 'Position', [ left bottom (1/cols) (1/rows) ] );
hold on
% (1) Draw the image
subimage(tmpImg, [0 255]);
axis off;
% (2) Plot the line over the original image
F = #(x) polyval(p, x);
fplot(F, [1 dimX 1 dimY], '-y');
}

Heatmap plots extra axes

I'm using the heatmap function in Matlab to plot some maps, the maps themselves are fine but the program seems to be adding extra borders and axes onto the figures, no idea why this is happening!
My code is:
figure(1)
hFig = figure(1);
set(gcf,'PaperPositionMode','auto')
set(hFig,'Position',[1000 1000 900 800])
colormap('hot');
imagesc(data)
xlabel('X({\mu}m)')
ylabel('Y({\mu}m)')
Here is an image of what I mean by extra axes:
Thanks!
Edit1: Here is the image after the first proposed fix:
Remove the xlabel and ylabel from the last lines of your code. Since you have already used the set function you can integrate them directly by doing
imagesc(data);
colomap('hot');
set(gca,'Xtick',[0:5:50],'XtickLabel',[0:5:50]);
set(gca,'Ytick',[0:5:50],'YtickLabel',[0:5:50]);
colorbar('YtickLabel',{'1000','900','800'});

How to specify the axis size when plotting figures in Matlab?

Suppose that I have 2 figures in MATLAB both of which plot data of size (512x512), however one figure is being plotted by an external program which is sets the axis parameters. The other is being plotted by me (using imagesc). Currently the figures, or rather, the axes are different sizes and my question is, how do I make them equal?.
The reason for my question, is that I would like to export them to pdf format for inclusion in a latex document, and I would like to have them be the same size without further processing.
Thanks in Advance, N
Edit: link to figures
figure 1: (big)
link to smaller figure (i.e. the one whose properties I would like to copy and apply to figure 1)
For this purpose use linkaxes():
% Load some data included with MATLAB
load clown
% Plot a histogram in the first subplot
figure
ax(1) = subplot(211);
hist(X(:),100)
% Create second subplot
ax(2) = subplot(212);
Now link the axes of the two subplots:
linkaxes(ax)
By plotting on the second subplot, the first one will adapt
imagesc(X)
First, you have the following:
Then:
Extending the example to images only:
load clown
figure
imagesc(X)
h(1) = gca;
I = imread('eight.tif');
figure
imagesc(I)
h(2) = gca;
Note that the configurations of the the first handle prevail:
linkaxes(h)
1.Get the handle of your figure and the axes, like this:
%perhaps the easiest way, if you have just this one figure:
myFigHandle=gcf;
myAxHandle=gca;
%if not possible, you have to search for the handles:
myFigHandle=findobj('PropertyName',PropertyValue,...)
%you have to know some property to identify it of course...
%same for the axes!
2.Set the properties, like this:
%set units to pixels (or whatever you prefer to make it easier to compare to the other plot)
set(myFigHandle, 'Units','pixels')
set(myAxHandle, 'Units','pixels')
%set the size:
set(myFigHandle,'Position',[x_0 y_0 width height]) %coordinates on screen!
%set the size of the axes:
set(myAxHandle,'Position',[x_0 y_0 width height]) %coordinates within the figure!
Ok, based on the answer of #Lucius Domitius Ahenoba here is what I came up with:
hgload('fig1.fig'); % figure whose axis properties I would like to copy
hgload('fig2.fig');
figHandles = get(0,'Children');
figHandles = sort(figHandles,1);
ax(1) = findobj(figHandles(1),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
ax(2) = findobj(figHandles(2),'type','axes','-not','Tag','legend','-not','Tag','Colorbar');
screen_pos1 = get(figHandles(1),'Position');
axis_pos1 = get(ax(1),'Position');
set(figHandles(2),'Position',screen_pos1);
set(ax(2),'Position',axis_pos1);
This is the 'before' result:
and this is the 'after' result:
Almost correct, except that the aspect ratios are still off. Does anybody know how to equalize everything related to the axes? (I realize that I'm not supposed to ask questions when posting answers, however adding the above as a comment was proving a little unwieldy!)