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!