How to plot (bar) a negative data in the first quadrant?
이전 댓글 표시
I have a set of data similar to the frequency spectrum. I want to plot that in MATLAB. The problem is that the magnitude (y) of data is a combination of negative and positives values. I want to plot it on the Y-axis as if it was positive, so the plot remains on the first quadrant, and I also like that the values show as negative and positive.
I tried following functions:
x = 0:1:10; %% x-axis data
y = [-1 -2 -4 -5 0 3 1 9 -2 -8 -1.5];
- bar(x,y); %% But it plots negative value magnitude in the fourth quadrant.
- stem (x,y); %% Plots negative values in the fourth quadrant.
- scatter(x,y); %% It will plot in the first quadrant but only shows the marker. I want a similar graph with a line joining to the x-axis.
- plot(x,y); %% doesn't work for me as I want spikes of magnitude (on y-axis) on particular values of x.
But, all of the above functions do not work because either it plots the negative values on the fourth quadrant or just giving discrete values without a line in the first quadrant. I want the graph in the first quadrant (above the x-axis) of the data.
Any help on how to do this? I have searched documentation and forums, and I couldn't find it.
댓글 수: 2
Adam Danz
2021년 5월 2일
Why not just apply abs() to the variable that you want to be positive?
Vijender Kumar Sharma
2021년 5월 2일
채택된 답변
추가 답변 (1개)
Scott MacKenzie
2021년 5월 1일
How about this:
% your test data
x = 0:1:10;
y = [-1 -2 -4 -5 0 3 1 9 -2 -8 -1.5];
% determine which values of y are negative
yNegative = y < 0;
% use custom colors (different color for negative y)
colorPos = [.6 .8 .9];
colorNeg = [.65 .9 .95];
clr = repmat(colorPos, length(y), 1);
clr(yNegative,1:3) = repmat(colorNeg,sum(yNegative),1);
% make all y values positive
y1 = abs(y);
% create the bar chart (all bars in 1st quadrant)
b = bar(x, y1, 'facecolor', 'flat');
ax = gca;
ax.YLim = [0 max(y)+1];
% set bar colors to custom colors (negative y in different color)
b.CData = clr;
% put data values above bars (showing negative values for y)
xn = b.XData;
yn = b.YEndPoints + 0.4;
s = string(y);
text(xn, yn, s, 'color', [.2 .2 .2], 'fontsize', 12, 'horizontalalignment', 'center');

카테고리
도움말 센터 및 File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
