set xticks by calculation but also force 0 to be displayed
조회 수: 15 (최근 30일)
이전 댓글 표시
I am setting xticks manually based on user inputs for distance. The plot will span the distance range; for example -1.3E-06 to 1.3E-06. The calculation works well to calculate the distance between tick marks, but depending on how it's done it may or may not automatically included 0 on the x axis. Is there a way I can force 0 to be displayed on the axis without altering my method for calculating the distance between tick marks.
댓글 수: 0
채택된 답변
Walter Roberson
2021년 6월 10일
format long g
%demonstration values
x = linspace(-1.4e-6,1.32e-6,29)
y = sinpi(2e6*x)
plot(x,y)
array_of_tick_values = -1.3e-6:.24e-6:1.3e-6
%force a 0
xticks(union(array_of_tick_values, 0))
However, this could result in two ticks being close together. For example if your calculated tick was at -1e-10 then you would get a tick at -1e-10 and at 0. In the above example plot you can see that the -0.1 tick is close to the 0 tick
Whereas...
plot(x,y)
xtrange = max(abs(array_of_tick_values));
array_of_tick_values = linspace(-xtrange,xtrange,length(array_of_tick_values));
xticks(array_of_tick_values)
댓글 수: 2
Walter Roberson
2021년 6월 10일
Hmmm I just realized that you need the linspace length to be odd to force going through 0.
추가 답변 (1개)
Joel Lynch
2021년 6월 10일
편집: Joel Lynch
2021년 6월 10일
set(gca,’XTick’,array_of_values)
댓글 수: 2
Walter Roberson
2021년 6월 10일
ismember(0, vector_of_values)
but that leaves the searching open in that form. But if the vector is sorted you could
idx = find(vector_of_values <= 0, 1, 'last')
if vector_of_values(idx) == 0
exact match for 0
else
vector_of_values = [vector_of_values(1:idx), 0, vector_of_values(idx+1:end)]
end
assuming row vector
... But the union() approach I posted is much more compact and has the same effect.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!