Is there a way to have a new line in an axis tick label in Matlab to produce a multiline tick label?
The two suggestions from here for other text elements don't seem to work:
set(gca,'xticklabel',{{'line1','line2'}})
fails, and
set(gca,'xticklabel',{['line1' 10 'line2']})
or
set(gca,'xticklabel',{['line1' 13 'line2']})
ignore the newline or carriage return. Any ideas?
I am not sure how long it has been around, but at least in R2015b the axes objects have a 'TickLabelInterpreter' property, which can be specified to set how the tick labels are interpreted. If you choose a LaTeX interpreter, it is possible to have multiline ticklabels quite easily by wrapping them in a tabular environment.
Example:
figure;
plot(rand(10,1));
%// Tick label with arbitrary number of lines in tabular environment
xtl = '\begin{tabular}{c} line 1 \\ line 2 \\ line 3\\ line 4\end{tabular}';
%// use the tick label at location 5 on the x axis
set(gca,'xtick', 5, 'XTickLabel', xtl, 'TickLabelInterpreter', 'latex');
Output:
Of course, the drawback here is that you need to use the LaTeX interpreter which somewhat changes the appearance of the figure. But I believe some people (such as me) actually prefer the way the LaTeX interpreted figure annotations look! As an added bonus, you can use whatever other LaTeX markup you desire (equations, etc.) in the labels.
I suggest you use fix_xticklabels() by Mikhail Erofeev. You can pad your tick labels with space character i.e. " " to adjust the output.
Related
Since MATLAB R2017a, figure legends update automatically when adding a plot to axes. Previously, one could do this:
data = randn(100,4);
plot(data)
legend('line1','line2','line3','line4')
hold on
plot([1,100],[0,0],'k-')
to plot four data lines with a legend, and then add a black line for y=0. However, since R2017a, this leads to the black line being added to the legend, with the name "data1".
How do I prevent this line from being added to the legend, so that the code behaves like it did in older versions of MATLAB?
The only solution I have found so far on Stack Overflow is to remove the legend item after it has been added. The syntax is not pretty:
h = plot([1,100],[0,0],'k-'); % keep a handle to the added line
set(get(get(h,'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
The release notes for MATLAB R2017a mention this change, and provide 4 different ways of handling the situation. These two methods are easiest to put into existing code:
1: Turn off auto updating for the legend before adding the black line. This can be done at creation time:
legend({'line1','line2','line3','line4'}, 'AutoUpdate','off')
or after:
h = findobj(gcf,'type','legend');
set(h, 'AutoUpdate','off')
You can also change the default for all future legends:
set(groot,'defaultLegendAutoUpdate','off')
2: Turn off handle visibility for the black line that you don't want added to the legend:
plot([1,100],[0,0],'k-', 'HandleVisibility','off')
The IconDisplayStyle method is also shown here. However, they use the dot notation, which makes the syntax is a bit prettier:
h = plot([1,100],[0,0],'k-'); % keep a handle to the added line
h.Annotation.LegendInformation.IconDisplayStyle = 'off';
I am trying to write a function that would take an indexed image as an input and will replace all its pixels by symbols or characters.
An image is worth more than a 1000 words: This is the desired look output. Each of the symbols represent an unique color value of the image.
My problem is that I don't know how to print in the screen the symbols in the correct place. My first approach has been to use the "Wingdings" font and to put text on the places, but does not work as expected. The text changes sizes when zoomed, and does not behave accordingly to the rest of the plot.
I leave here a small piece of code that creates a small grid and uses an example image.
function drawChars (img)
if nargin==0
load mandrill
img=X(1:4:end,1:4:end);
end
chars=randperm(numel(unique(img)));
[h,w]=size(img);
% Form a grid
figure
hold on
for ii=0:h
plot([ii ii],[0 w],'k');
end
for ii=0:w
plot([0 h],[ii ii],'k');
end
axis equal;
axis([0 h 0 w])
%% This does not work as expected
for ii=1:h
for jj=1:w
text(ii, jj, char(chars(img(ii,jj))), 'fontname', 'Wingdings', 'fontsize',10);
end
end
end
Short question: What approach would you use to solve the problem?
NOTE: there is a problem with the choice of chars also, but ignore it for the time being (if char { is chosen does not work nicely)
With figure changed to f=figure
r=size(img).*16;
set(f,'paperunits','points')
set(f,'papersize',r)
set(f,'paperposition',[0 0 r]);
print(f,'example.png','-dpng');
Prints the created figure to a png of sufficient size.
I have created a graph with data from an Excel file. I need to keep all the xticks but the xticklabels to appear just on every 6 ticks. I have tried doing this:
tickStep=6;
Sheet=2;
filename='MyData.xlsx';
[~,xAxis]=xlsread(filename,Sheet,'A2:A60');
yAxis=xlsread(filename,Sheet,'B2:B60');
plot(1:numel(xAxis),yAxis)
set(gca,'xtick',1:numel(xAxis))
set(gca,'xticklabel',xAxis(1:tickStep:numel(xAxis)))
Unfortunately it does not work as all the xticks are plotted, but the xticklabels appear upon each xtick instead of every 6th like I was trying to achieve. I have spent quite a long time thinking about the solution:-(. I need help. Thanks.
edit: I've included an image to help answer questions below:
In relation to this post, would it also be possible that the xticks appear every 4 xticks instead of keeping all of them, at the same time that the xticklabels are plotted every 6 xticks?, not sure about this.
You still need to enter an empty string (or empty cell) for the ticks that will have no label. You can do this by replacing the last line with these three lines:
xTickLabels = cell(1,numel(xAxis)); % Empty cell array the same length as xAxis
xTickLabels(1:tickStep:numel(xAxis)) = xAxis(1:tickStep:numel(xAxis));
% Fills in only the values you want
set(gca,'XTickLabel',xTickLabels); % Update the tick labels
Edit in response to questions below...
The reason your labels appear to be offset from the ticks is because the bottom of the letters appears to be getting lined up with the tick mark. I'm guessing you want the text justified such that the center of each letter lines up with the tick mark. There's no way to do this with the standard MATLAB axes, but there are some submissions on the MathWorks File Exchange that convert the tick labels to text objects and thus give you more options for customizing the text properties:
XTICKLABEL_ROTATE by Brian Katz
Format Tick Labels by Alexander Hayes
Once you convert the labels to text objects, you can then adjust the rotation or vertical justification by modifying the 'Rotation' and 'VerticalAlignment' properties, respectively.
Log plots in MATLAB only label the axes at positions 10^x, where x is an integer (e.g., 10^4, 10^5, 10^6). Sometimes, one may want labels at intermediate sites or minor ticks (e.g., 5*10^4, 5*10^5).
In order to place such labels, I have resorted to using the text command with appropriate x and y coordinates. However, the font of the superscript in the text command differs from that in the default axis label. This is true even if the font for axis label and text is set to be identical by the following:
set(0,'DefaultAxesFontName','Helvetica');
set(0,'DefaultTextFontName','Helvetica');
set(0,'DefaultTextFontSize',15);
set(0,'DefaultAxesFontSize',15);
In particular, the superscript font size appears to be smaller in the default axis label compared to the text box. Is there a way to resolve this discrepancy so that the font in the text box and the font in the axis label are identical (including superscripts)?
You can set the x and y axis points like this:
figure
set(gca,'xtick',10.^[0.5:0.5:3])
set(gca,'ytick',10.^[0.5:0.5:3])
gives you steps in 0.5 log 10. There is also an attribute called xticklabel
EDIT: Here's a complete example using arbitrary labels, scientific notation:
semilogx([2:100:10e4],[2:100:10e4])
axis([2 2e4 2 10000])
xticks=10.^[0.5:0.5:10]';
al={};
for i = 1:length(xticks)
tmps=sprintf("%1.1e}",xticks(i));
tmps=strrep(tmps,"e","x10^{"); # replace e with x10^{
tmps=strrep(tmps,"+0",""); # +0 does not add any info
tmps=strrep(tmps,"-0","-"); # -0123 into -123
tmps=strrep(tmps,"+",""); # + does not add any info
al(i)=tmps;
end
set(gca,'xtick',xticks);
set(gca,'xticklabel',al)
I want to add a x-axis line at 0 to a Matlab figure so that I can compare my data to see if it is positive or negative when saving the figures to a jpg. What is the best way to do this? I know you can use line() but it just seems cumbersome because you need to specify the x and the y ranges. Is there an easier way?
There exist an undocumented function graph2d.constantline:
plot(-2:5, (-2:5).^2-1)
%# vertical line
hx = graph2d.constantline(0, 'LineStyle',':', 'Color',[.7 .7 .7]);
changedependvar(hx,'x');
%# horizontal line
hy = graph2d.constantline(0, 'Color',[.7 .7 .7]);
changedependvar(hy,'y');
The nice thing is that it internally implements a listener for the axes limits (handles change like pan, zoom, etc..). So the lines would appear to extend to infinity.
You could get this x range directly after the figure has been created. It goes a little something like this:
x=-2:5;
y=x.^2-1;
figure()
plot(x,y);
xlim = get(gca,'xlim'); %Get x range
hold on
plot([xlim(1) xlim(2)],[0 0],'k')
Note that if you do any manual zooming out in the figure, the line might have to be redrawn to go over the entire new x range.
I don't believe there is a built-in way that is more convenient. I use hline() and vline() from FileExchange, which work like a charm:
http://www.mathworks.com/matlabcentral/fileexchange/1039
A vline and hline command like in GNU R would be great, but I could not find a shorter solution than
plot(1:10,sin(1:10));
line(xlim,[0 0],'Color','r')
Draw your data by plot() command or stem(). A figure window will open.
Then on the figure window, click on the [insert] command from the
menu bar, a drop-down menu will appear.
From this menu click on the [line] command, now the shape of the
cursor will change into a plus sign.
Now you can draw a line anywhere you want, either horizontal or
vertical or slanted.
You can change the properties of line by right clicking on the
line, a menu will appear from which you can choose your desires
properties.
If you want to have some ticks on the line then you can use add
text option, and place text where ever you want.
If you would like to have a code for your figure, click on [file]
menu and then click on [generatecode] option, a new text editor
window will open, you can save this code for further use. Good luck.
Since MATLAB R2018b there is yline for this purpose:
yline(0)
draws a horizontal line at y==0.