Bar chart with numerical x-axis treated as labels OR with thicker "bars"
5 次查看(过去 30 天)
显示 更早的评论
I want to create bar charts where a list is used to form the labels for the x-axis, but the list is a list of numbers. Here's an example
xaxislabels = [0.1; 0.2; 0.5; 1; 2; 5; 10; 20; 30; 40]
barlengths = [10; 30; 62; 71; 84; 172; 1423; 3026; 0; 0]
bar(xaxislabels,barlengths)
bar(barlengths)
If I use the first option, I get very thin bars that are almost like pencil lines. From what I've read it is not possible to make these bars thicker. I tried playing with a log2 scale on the axis to get thicker bars, but could only do that by scaling the x-axis values, and then the labels are not what I need.
If I use the second option I loose the spacing along the x-axis, but at least it is looking like what people expect. I'd like to use the xaxislabels to label each of the bars. I know I can do
X = categorical({'0.1','0.2', '0.5','1', '2', '5', '10','20', '30', '40'})
X=reordercats(X,{'0.1','0.2', '0.5','1', '2', '5', '10','20', '30', '40'})
bar(X,barlengths)
However that requires that I know in advance what those labels should be, but they are read in from a CSV file and will change depending on which parameter set is selected. I have tried following advice to turn the numbers into categorical using discretize however either that doesn't apply in this case, or I'm doing something wrong. I also just tried to turn it into a string and then into a categorical using categorical(num2str(xaxislabels)) but that doesn't work either.
0 个评论
采纳的回答
Mohammad Sami
2020-4-1
编辑:Mohammad Sami
2020-4-1
categorical does not need you to supply the values as cellstring or string. You can straight away use it on a numerical array.
xaxislabels = [0.1; 0.2; 0.5; 1; 2; 5; 10; 20; 30; 40];
barlengths = [10; 30; 62; 71; 84; 172; 1423; 3026; 0; 0];
bar(categorical(xaxislabels),barlengths)
As long as xaxislabels are sorted, this should work. if not sorted then you will need to sort it.
xaxislabels = [0.1; 0.2; 0.5; 1; 2; 5; 10; 20; 30; 40];
barlengths = [10; 30; 62; 71; 84; 172; 1423; 3026; 0; 0];
[~,i] = sort(xaxislabels);
xaxislabels = xaxislabels(i);
barlengths = barlengths(i);
bar(categorical(xaxislabels),barlengths)
This is valid for when x axis is already discrete value as above.
If you have data with continous x values, you can use discretize instead
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Bar Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!