How to plot (bar) a negative data in the first quadrant?
Afficher commentaires plus anciens
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 commentaires
Adam Danz
le 2 Mai 2021
Why not just apply abs() to the variable that you want to be positive?
Vijender Kumar Sharma
le 2 Mai 2021
Réponse acceptée
Plus de réponses (1)
Scott MacKenzie
le 1 Mai 2021
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');

Catégories
En savoir plus sur Discrete Data Plots 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!
