Too many x labels on bar graph
조회 수: 11 (최근 30일)
이전 댓글 표시
Hi,
I'm trying to plot a categorical array against a respective double, but have filtered the indexes for values > 2. I.e., assume we have categorical array 'x', with the respective y-axis values 'y'. This ultimately cuts-down the size of the arrays from 100x1, to 30x1.
yindx = y>3;
x = x(yindx);
y = y(yindx);
The resultant filtered arrays look completely correct. However, when I plot it into a bar graph 'bar(x,y)', the x-labels for the filtered values are still present, but the corresponding y-values aren't plotted. So I can see all 100 original x-labels, but only the 30 filtered y-value bars.
How can I remove the unwanted x-labels from the graph, to only leave the corresponding 30 labels on the x-axis?
댓글 수: 2
답변 (2개)
Bala Tripura Bodapati
2022년 9월 30일
Hi Harley
It is my understanding that after filtering the categorical array and plotting the values, all the categories are displayed on the bar graph instead of the filtered categories.
On creating a categorical array, all the unique categories get stored in the assigned variable. On filtering this array using indexing, the array values will be filtered but the categories stored will not be affected. This can be verified by executing the 'categories' function on the filtered array.
To display only the filtered categories on the bar graph, the following workarounds can be considered:
1. Each element of the categorical array is unique: Remove the categories not present in the filtered array using removecats function. The following code illustrates this use-case:
x=["a","b","c","d","e","f"]
x=categorical(x)
y=[1,2,3,5,6,8]
yindx=y>3
x_unfiltered_categories=string(x(~yindx))
x=x(yindx)
y=y(yindx)
x=removecats(x,x_unfiltered_categories)
bar(x,y)
2. Each element of the categorical array is not unique: Convert the filtered categorical array to string and then back to categorical. The following code illustrates this use-case:
x=["a","b","c","a","b","f"]
x=categorical(x)
y=[1,2,3,5,6,8]
yindx=y>3
x=x(yindx)
y=y(yindx)
x=categorical(string(x))
bar(x,y)
댓글 수: 0
Siddharth Bhutiya
2022년 10월 3일
편집: Siddharth Bhutiya
2022년 10월 3일
When plotting the categorical it will plot all the categories that were defined when creating the categorical. If you want the plots to not show the categories not present in the new subset then call removecats before plotting. Calling removecats with just one input argument will remove any unused categories from your categorical array.
>> x = categorical(1:10);
>> y = x(4:8);
>> bar(y,4:8) % Plots all categories 1 2 .... 9 10
>> y = removecats(y);
>> bar(y,4:8) % Only plots 4 5 ... 7 8
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Categorical Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!