How to plot (bar) a negative data in the first quadrant?
조회 수: 6 (최근 30일)
이전 댓글 표시
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
채택된 답변
Scott MacKenzie
2021년 5월 2일
The "wrong information" was in your question, as posted. I'll admit that my original solution was a bit odd, but it faithfully rendered what you described (which I thought was a bit odd in the first place). If you had posted the figure in your original question and/or provided a clear description of the goal, we could have saved some back-and-forth commenting. Anyway, not to worry. I think is what you are looking for is below. All you need to do is set the BaseValue property of the stem (or bar) graph. Good luck.
% your test data
x = 0:1:10;
y = [-1 -2 -4 -5 0 3 1 9 -2 -8 -1.5];
h = bar(x,y);
h.BaseValue = -10;
h.LineWidth = 2;
h.Color = 'k';

추가 답변 (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');

참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!