[英]How to plot bar graph to compare two quantities on y-axis at specific values on x-axis?
[英]Plot in a different colors for y-values above x-axis
在這里我繪制了((2*x.^2+3*exp(-x) -(100*a)).*sin(5*x))./(6*x.^2-9*x-42)-10
輸入a=3
, dx=0.1
。
我想要 plot 藍色的所有正 y 值和紅色的所有負 y 值:
a = input('Please input a: ');
dx = input('Input step size dx: ');
if dx<0
fprintf('dx must be a non-negative number.');
while(dx<0)
dx = input('Input step size dx: ');
end
end
clf;
x = -10:dx:10;
y = ((2*x.^2+3*exp(-x) -(100*a)).*sin(5*x))./(6*x.^2-9*x-42)-10
plot(x,y)
ylim([-100,100])
對於 plot 藍色的正 y 值和紅色的負 y 值,我嘗試為正 y 值及其域初始化向量,為負 y 值及其域初始化相同的向量。
s = size(y);
x_1 = [];
x_2 = []; %negative
y_1 = [];
y_2 = []; %negative
for i = 1:s(2)
if(y(i) >0)
x_1 = [x_1,x(i)];
y_1 = [y_1,y(i)];
elseif (y(i) <0)
x_2 = [x_2,x(i)];
y_2 = [y_2,y(i)];
end
end
s_x1 = size(x_1);
s_x1_lim = s_x1(2);
s_x2 = size(x_2);
s_x2_lim = s_x2(2);
plot(x_1,y_1,'b');
xlim([x_1(1), s_x1_lim]);
hold on
plot(x_2,y_2,'r');
xlim([x_2(1), s_x2_lim]);
hold on;
xlim([-10,10])
ylim([-100,100]);
問題是,這種方法留下了一些我不希望有的重疊。 我怎樣才能改變這個?
你可以做兩個 arrays: neg_x = x; neg_x (neg_x >0) = nan
neg_x = x; neg_x (neg_x >0) = nan
plot 使用'r'
然后正值相反。 但是,這會給您留下兩個 arrays 之間的部分,即您的差距。 您可以通過找到它們並將索引擴展一個來更正它們:
x = 0:0.1:6*pi;
y = sin(x);
neg_y = y; neg_y (neg_y>0) = nan;
tmp_y = isnan(neg_y);
idx = find(diff(tmp_y)==1); % find gaps
neg_y(idx+1) = y(idx+1); % correct gaps
idx = find(diff(tmp_y)==-1);
neg_y(idx) = y(idx);
pos_y = y; pos_y (pos_y<0) = nan;
plot(x, neg_y,'r');
hold on;
plot(x,pos_y,'b')
使用nan
在這里有點幫助,因為 MATLAB 在繪圖時會自動忽略這些條目,即留下一個很好的間隙,而不是一條直線。
結果是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.