How to label specific increments

So this is my code:
x = linspace(0,2*pi,100);
y1 = cos(x).^2;
plot(x,y1,'--r')
ylim([-1 1])
xticks(0:pi/100:2*pi)
hold on
y2 = sin(x.^2);
plot(x,y2,'b')
hold off
legend('cos^2(x)','sin(x^2)')
xlabel('x')
ylabel('y')
title('Plot of y1=cos^2(x) and y2=sin(x^2)')
and i set it so there is a increment every pi/100, but i only want it to show a label for 0, pi/2, pi, 3pi/2, and 2pi. With the code I have set up right now, this is a label for every increment so the numbers at the bottom are jumbled together.

Réponses (2)

Ameer Hamza
Ameer Hamza le 2 Oct 2020

0 votes

Set the ticks and minor ticks seperately
x = linspace(0,2*pi,100);
y1 = cos(x).^2;
y2 = sin(x.^2);
ax = axes();
hold on
plot(x,y1,'--r')
ylim([-1 1])
ax.XMinorTick ='on';
ax.XAxis.MinorTickValues = 0:pi/100:2*pi;
ax.XTick = (0:1/2:2)*pi;
ax.XTickLabel = {'0', '\pi/2', '\pi', '3\pi/2', '2\pi'};
plot(x,y2,'b')
hold off
legend('cos^2(x)','sin(x^2)')
xlabel('x')
ylabel('y')
title('Plot of y1=cos^2(x) and y2=sin(x^2)')
Star Strider
Star Strider le 2 Oct 2020

0 votes

Try this:
x = linspace(0,2*pi,100);
y1 = cos(x).^2;
plot(x,y1,'--r')
ylim([-1 1])
xticks(0:pi/100:2*pi)
xticklabels({});
xtv = 0:pi/100:2*pi;
idx = find(ismembertol(xtv,[0, pi/2, pi, 3*pi/2, 2*pi], 0.001));
xtl = {'0','$\frac{\pi}{2}$','$\pi$','$\frac{3\pi}{2}$','$2\pi$'};
text(xtv(idx), min(ylim)*ones(size(idx)), xtl, 'Interpreter','latex', 'HorizontalAlignment','center', 'VerticalAlignment','top')
xlim([min(x) max(x)])
hold on
y2 = sin(x.^2);
plot(x,y2,'b')
hold off
legend('cos^2(x)','sin(x^2)', 'Location','SW')
xlabel('x')
ylabel('y')
title('Plot of y1=cos^2(x) and y2=sin(x^2)')
producing:
.

Catégories

En savoir plus sur Environment and Settings dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by