I am using Matlab version R2014a and I am trying to have plot look like the Simulink scope. My code works as it should except, the ColorOrder setting is not reflected in the output.
Right after setting ColorOrder I retrieved it with current_co=get(gca, 'ColorOrder'); and it gives back the value that I have set. However in the diagram the default colors are used.
Why is this? How can it be fixed?
my_co=[1.0 1.0 0.0; 1.0 0.0 1.0; 0.0 1.0 1.0; 1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0; 1.0 1.0 1.0];
figure('Color', [0.2 0.2 0.2]);
plot(ScopeData(:,2:6));
legend('w(t)','e(t)','y(t)','x(t)','z(t)');
set(gca, 'ColorOrder', my_co);
set(gca, 'Color', 'black');
set(gca, 'XColor', 'white');
set(gca, 'YColor', 'white');
set(gca, 'XGrid', 'on');
set(gca, 'YGrid', 'on');
title('My funky title!', 'Color', 'white');
xlabel('t/[s]');
You have to set the ColorOrder property before plotting anything. Plot objects respect the current value of the ColorOrder property when they are created and changing the ColorOrder after they are created only has an effect on future plots. Also note that you need to call hold on prior to plotting anything to prevent the axes from going back to the default ColorOrder.
my_co = [1 1 0; 1 0 1; 0 1 1; 1 0 0; 0 1 0; 0 0 1; 1 1 1];
figure('Color', [0.2 0.2 0.2]);
% Set this before plotting anything
set(gca, 'ColorOrder', my_co);
hold on
% NOW plot your data
plot(ScopeData(:,2:6));
legend('w(t)','e(t)','y(t)','x(t)','z(t)');
set(gca, 'ColorOrder', my_co);
set(gca, 'Color', 'black');
set(gca, 'XColor', 'white');
set(gca, 'YColor', 'white');
set(gca, 'XGrid', 'on');
set(gca, 'YGrid', 'on');
title('My funky title!', 'Color', 'white');
xlabel('t/[s]');
% If you want you can turn hold off now
hold off
This makes sense because if you create a plot using a custom color:
plot(data, 'Color', 'magenta')
You wouldn't want the axes automatically changing this manual color when the ColorOrder property is changed.
Related
I'm plotting some simple figures and save them into TIFF images using print function. But in my saved images the lines are very thick and the texts are very big. So I have to set the LineWidth and FontSize to a very small value to make sure my figure looks good. For now I set LineWidth to 0.05. And in my opinion for a 72dpi image it should be 0.05 pixels wide. But in my image it seems to be 1 pixel. However, if I set LineWidth to 1 I get the axes borders' width of about 10 pixels! (I suppose it should be 1pt * 1/72in/pt * 72px/inch = 1px). Am I doing wrong?
One thing to mention: My image is very high(324 inches) as I have 36 subplots in a column.
Following are my code. Notice that I set the border width of the axes to 1.
function [ ] = draw_seq_1( raw_years, year_rng, raw_data, name, datarng )
year_span = year_rng(1):year_rng(end);
data = raw_data(:, find(raw_years==year_rng(1)):find(raw_years==year_rng(end)));
figure(1);
set(gcf, 'Visible', 'off');
base_pos = [0, 0, 18, 6 * size(data,1)];
set(gcf, 'PaperPositionMode', 'manual');
set(gcf, 'unit', 'inches');
set(gcf, 'position', base_pos);
set(gcf, 'paperunits', 'inches');
set(gcf, 'paperposition', base_pos);
for i = 1:size(data,1)
data_to_plot = data(i,:);
subplot(size(data,1),1,i);
plot(year_span, data_to_plot, 'LineWidth', 0.1, 'Color', [0.4 0.6 0.7]);
hold on;
plot(year_span, 1+zeros(size(year_span)), 'LineWidth', 0.1, 'Color', [0 0 0]+0.5, 'LineStyle', '--');
title(sprintf('%s(%d-%d) # %d', name, year_rng(1), year_rng(end), datarng(1)+i-1));
set(gca, 'YLim', [0, max(0.1, max(data_to_plot)*1.05)] );
set(gca, 'YTick', [0, 1, 2, 3, 4, 5]);
% here set the border width of the axes
set(gca, 'LineWidth', 1);
set(gca, 'FontSize', 1);
set(gca, 'FontUnit', 'points');
end
print(gcf, sprintf('%s(%d-%d) # %d-%d.tiff', name, year_rng(1), year_rng(end), datarng(1), datarng(end)), '-dtiff', '-r72');
end
My saved images is below. You can see that the border width is very thick.
I would like to have a tight subplot i.e. minimum spacing between figures in the subplot where
you have subplot's 3rd parameter i.e. you can decide where the picture is going to be i.e. easy to move between subplot and new_tight_subplot, and
you can use it with colorbars.
I have profiled the most popular tight subplots in FileExchange of Matlab.
None (etc most popular here Pekka's version) can pass the following code
data=randi(513,513);
ax1=subplot(2,1,1);
plot(mat2gray(pdist(data, 'correlation')));
cbar1=colorbar(ax1);
axis(ax1, 'square');
xlim([0 size(mat2gray(pdist(data, 'correlation')),2)]);
set(cbar1, 'Visible', 'off')
ax2=subplot(2,1,2);
imshow(squareform( mat2gray(pdist(data, 'correlation')), 'tomatrix') );
colormap('parula'); colorbar;
axis(ax2, 'square');
Pekka's tight_subplot requires the syntax without the third parameter.
It also fails with colorbars as in the example. I do not understand why.
Hypothesis about the 2nd problem with colorbars
I think the problem can be the fact that colorbar objects are children of the figure, not axis, and their position is defined in normalized figure units; like for annotated objects as discussed here.
However, I am unsure how to adjust the tight subplot for this.
Test output after Author's edit in tight_subplot in FileExchange 3.3.2016
Code
data = randi(513, 513);
ax1=tight_subplot(2,1,[.01 .03],[.1 .01],[.01 .01]);
plot(mat2gray(pdist(data, 'correlation')));
ax2=tight_subplot(2,1,[.01 .03],[.1 .01],[.01 .01]);
imshow(squareform( mat2gray(pdist(data, 'correlation')), 'tomatrix') );
You get
where the plot fails and there is noisy part in the second figure for some reason. Why?
Extension of Suever's answer to 2x2 figures
ax1=axes('OuterPosition', [0 0.5 0.5 0.5]);
plot(u, 'Parent', ax1);
set(ax1, 'XLim', [0, size(u,1)]);
cbar1 = colorbar(); % not needed to assign ax1
set(cbar1, 'Visible', 'off')
ax3 = axes('OuterPosition', [0 0 0.5 0.5]);
image(data, 'Parent', ax3);
D=mat2gray(pdist(pTFD, 'correlation'));
ax2 = axes('OuterPosition', [0.51 0.5 0.5 0.5]);
plot(D, 'Parent', ax2);
set(ax2, 'XLim', [0, size(D,1)])
axis(ax2, 'square');
xlim([0 size(D,2)]);
set(cbar2, 'Visible', 'off')
ax4 = axes('OuterPosition', [0.51 0 0.5 0.5]);
imshow( D_square );
axis(ax4, 'square');
where 2x2 figure system and where I think equivalent
xlim([0 size(D,2)]); is same as set(ax1, 'XLim', [0, size(D,2)]);. Right?
...
How can you use Matlab's tight subplot with colorbars and third parameter?
The third parameter of tight_subplot defines the gaps between axis objects. For the built-in subplot command, the third parameter defines which axis is set as the CurrentAxes of the Figure. This option is not available in tight_subplot because I personally did not find it useful. Typically, I use the returned axes handles to specify where to add graphics.
Existing axes objects are repositioned when you add a colorbar.
I have added a second output argument to tight_subplot which provides the output position of the axes so that you can "reset" the axes positions after adding a colorbar.
[hax, position] = tight_subplot();
% Add a colorbar which alters the positions
colorbar();
% Now reset the positions back to where they were
set(hax, {'Position'}, pos);
Rather than trying to deal with subplot and different versions on the file exchange, I would probably just manually set the positions of my axes objects to get the effect that you want. You can use normalized units so that the positions scale as the size of the parent figure changes.
Also, you can set the OuterPosition property of the axes which takes into account the room needed to properly display all text labels of the axes.
figure
data=randi(513,513);
set(0, 'defaultaxeslooseinset', [0 0 0 0])
D = mat2gray(pdist(data, 'correlation'));
square = squareform(D, 'tomatrix');
% Set normalized outer position (x,y,width,height)
ax1 = axes('OuterPosition', [0, 0.5, 1, 0.5]);
plot(D, 'Parent', ax1);
set(ax1, 'XLim', [0, size(square, 1)])
axis(ax1, 'square');
cbar1 = colorbar();
set(cbar1, 'Visible', 'off')
% Set normalized outer position (x,y,width,height)
ax2 = axes('OuterPosition', [0 0 1 0.5]);
imshow(square);
colormap('parula'); colorbar;
axis(ax2, 'square');
And if you remove the x and y ticks on the axes
set([ax1,ax2], 'xtick', [], 'ytick', []);
This can easily be adapted to any dimensions with something similar to the following
figure;
% [Rows, Columns]
axdim = [3, 3];
width = 1 ./ axdim(2);
height = 1./ axdim(1);
[x,y] = meshgrid(linspace(0,1,axdim(2)+1), ...
linspace(0,1, axdim(1)+1));
for k = 1:numel(x)
ax = axes('OuterPosition', [x(k), y(k), width, height]);
set(ax, 'xtick', [], 'ytick', []);
end
I would like to have vertical/horizontal grid lines across spacing of figures in Matlab 2015b.
I know that you can have a background image that can be a network of gridlines by background, something partial about it at How do I add a background image to my GUI or figure window?
However, I think gridlines without a picture would be a better choice
Example code
data=randi(513,513);
D=mat2gray(pdist(data, 'correlation'));
ax2 = axes('OuterPosition', [0.51 0.5 0.5 0.5]);
plot(D, 'Parent', ax2);
set(ax2, 'XLim', [0, size(D,1)])
axis(ax2, 'square');
title('Corr pdist');
cbar2 = colorbar();
set(ax2, 'XLim', [0 size(D,2)]);
set(cbar2, 'Visible', 'off')
grid minor;
% Force a draw event to have the axes determine where the
labelconverter = #(x)sprintf('%.2g', x); % https://stackoverflow.com/a/35780915/54964
callback = #(varargin)set(ax2, 'xticklabels', arrayfun(labelconverter, get(ax2, 'xtick'), 'uniform', 0));
set(hFig, 'SizeChangedFcn', callback);
callback(); % necessary for the original small window and its scientific numbering
D_square=squareform(D, 'tomatrix');
ax4 = axes('OuterPosition', [0.51 0 0.5 0.5]);
imshow( D_square );
colormap('parula'); colorbar;
axis(ax4, 'square');
title('Square Corr pdist');
where the system is based on relative positions, rather than subplot as described in the answer here about Tight subplot with colorbars and subplot's 3rd parameter in Matlab?
Hypothetical methods
have master figure which has grid lines; embed those two figures there as parent positions; not sure if possible
assign gridlines function to the function background
have a separate background image which has static gridlines
Function about Suever's script
function [ hFig ] = init_background_grid(thickness)
%% Background
hFig=figure;
backax = axes('Parent', hFig);
% Ensure that this is below other objects
uistack(backax, 'bottom');
% Span the whole figure
set(backax, 'Position', [0 0 1 1]);
grid(backax, 'on')
% Make it invisible except for the grid and
% ensure it isn't able to be interacted with
set(backax, 'HitTest', 'off', ...
'HandleVisibility', 'off', ...
'GridLineStyle', '-', ...
'Color', 'none', ...
'XColor', 'none', ...
'YColor', 'none')
% Determine grid spacing with x/y ticks
% Increase nLines for a finer grid
nLines = thickness; % 30 default
set(backax, 'XTick', linspace(0, 1, nLines), ...
'YTick', linspace(0, 1, nLines));
end
How can you have grid lines in the background i.e. in the spacing between figures?
I would probably just setup an axes that spans your entire figure, then turn on the grid lines, then set the color of the axes to 'none'. A full example is shown below.
fig = figure();
backax = axes('Parent', fig);
% Ensure that this is below other objects
uistack(backax, 'bottom');
% Span the whole figure
set(backax, 'Position', [0 0 1 1]);
grid(backax, 'on')
% Make it invisible except for the grid and
% ensure it isn't able to be interacted with
set(backax, 'HitTest', 'off', ...
'HandleVisibility', 'off', ...
'GridLineStyle', '-', ...
'Color', 'none', ...
'XColor', 'none', ...
'YColor', 'none')
% Determine grid spacing with x/y ticks
% Increase nLines for a finer grid
nLines = 20;
set(backax, 'XTick', linspace(0, 1, nLines), ...
'YTick', linspace(0, 1, nLines));
You can then add any plots, uicontrols, etc. on top of this and it should work just fine. It will also handle the case where you decide that you want a different figure color.
I get the following figure with a bar plot :
I would like to remove the XTick with red circles but keep Xtick for the middle of each group of bars (i.e 1024, 10240, 102400, 1024000, 10240000).
I generate this image with the Matlab script below :
x = load('performances.txt');
% Get Runtimes
for i = 1:6
time_seq(1:5,i) = x((i-1)*5+1:i*5,3);
time_gpu(1:5,i) = x((i-1)*5+1:i*5,4);
speedup(1:5,i) = time_seq(1:5,i)./time_gpu(1:5,i);
end
% X axis
sizeArray = [1024 10240 102400 1024000 10240000 102400000]
figure(1);
% Get Histogram
h = bar(log10(sizeArray),log10(speedup(1:5,:)')); % get histogram
% Log10 for x-axis and xtick
set(gca,'Xtick',log10(1024):1:log10(1.024*10^8))
set(gca,'Xticklabel',10.^get(gca,'Xtick'));
set(h(1),'facecolor',[0.5 0.5 1]);
set(h(2),'facecolor',[1 0.5 0.5]);
set(h(3),'facecolor',[0.5 1 0.5]);
set(h(4),'facecolor',[0.5 0.5 0.5]);
set(h(5),'facecolor',[1 0.5 1]);
hPatch = findobj(h,'Type','patch');
set(hPatch,'facealpha',1);
grid on;
title('Benchmark GPU vs CPU');
% Size of WorkGroup
h = legend('N=16','N=32','N=64','N=128','N=256');
v = get(h,'title');
set(v,'string','WorkGroup size');
% Place legend
rect = [0.6,0.25,0.2,0.2];
set(h,'Position',rect,'color','w');
hPatch = findobj(h,'Type','patch');
set(hPatch,'facealpha',1);
xlabel('log(Array size)');
ylabel('log(Speedup)');
% Make right y-axis visible
ax1 = gca;
ax2 = axes('Position', get(ax1, 'Position'));
set(ax2, 'YAxisLocation', 'right', 'Color', 'none', 'XTickLabel', []);
set(ax2, 'YLim', get(ax1, 'YLim'));
I tried different things but couldn't make them disappear, anyone would have an idea or a clue ?
Thanks
It happens because of the last 3 lines in your code where you add the Y-axis from the right side. You need to add the following line at the end:
set(ax2,'XTick',[]);
Here is my result (with fake data):
Matlab 2015b or Matlab 2016a.
I would like to have grid lines going across Subplot's spacing between the figures in order to evaluate better two pictures horizontally.
However, I have a small gap between the two figures at the lower right-hand-side corner because which is misaligning the figures
where the gap is because of the 10^4 at lower right-hand-side corner.
I would also like to have horizontal lines going across the spacing between the two figures, but I cannot do it before the gap problem is solved.
Code where the relative alignment is done as described in the answer here about the thread Tight subplot with colorbars and subplot's 3rd parameter in Matlab?
data=randi(513,513);
D=mat2gray(pdist(data, 'correlation'));
% Set normalized outer position (x,y,width,height)
ax1=axes('OuterPosition', [0 0.5 0.5 0.5]);
plot(D, 'Parent', ax1);
xlim([0 size(D,2)]);
set(cbar1, 'Visible', 'off')
title('Signal');
ax2=axes('OuterPosition', [0.51 0.5 0.5 0.5]);
plot(D, 'Parent', ax2);
set(ax2, 'XLim', [0, size(D,1)])
axis(ax2, 'square');
title('Corr pdist');
Output of Suever's answer
I tried unsuccessfully change two (2) in sprintf('%.2g', x) bigger and smaller
ax2 = axes('OuterPosition', [0.51 0.5 0.5 0.5]);
plot(D, 'Parent', ax2);
set(ax2, 'XLim', [0, size(D,1)])
axis(ax2, 'square');
title('Corr pdist');
cbar2 = colorbar(); % ax2 not needed here in brackets
set(ax2, 'XLim', [0 size(D,2)]);
set(cbar2, 'Visible', 'off')
grid minor;
% https://stackoverflow.com/a/35776785/54964
xticks = get(ax2, 'xtick');
labels = arrayfun(#(x)sprintf('%.2g', x), xticks, 'uniform', 0);
set(ax2, 'xticklabels', labels);
It gives
where those ticks are not XMinorTicks but simply ticks (wrongly marked in the picture).
They are zero points at some points in the x-axis. When x-axis gets larger, MATLAB automatically adds new xtick marks but without complete labels.
I think it would be better to have another symbol than zero there. How can you have some other mark than zero for incomplete labels of xticks?
How can you align the 10^4 next to the last number in the second figure?
I would get the current xtick locations, convert those to strings, and then set the xticklabels property of the axes.
xticks = get(ax2, 'xtick');
labels = arrayfun(#(x)sprintf('%.2g', x), xticks, 'uniform', 0);
set(ax2, 'xtick', xticks, 'xticklabels', labels);
If you want them to dynamically be computed as the figure changes size (and the xticks get recomputed) you can link this code to the SizeChangedFcn of the figure.
func = #(varargin)set(ax2,'xticklabels',arrayfun(#(x)sprintf('%.2g',x),get(ax2, 'xtick'),'uni',0));
set(gcf, 'SizeChangedFcn', func)