MATLAB Answers

Bar graph labels not aligning with index value

16 ビュー (過去 30 日間)
Sam Acker
Sam Acker 2021 年 2 月 18 日
回答済み: Rik 2021 年 2 月 19 日
I'm trying to create a bar graph for the number of US state name mentions in a certain body of text. When I try to assign state names as the x-axis labels to my bar graph, the labels do not coincide with their corresponding index value. Here's my code:
states = {'Alabama' 'Alaska' 'Arizona' 'Arkansas' 'California'...
'Colorado' 'Connecticut' 'Delaware' 'Florida' 'Georgia'...
'Hawaii' 'Idaho' 'Illinois' 'Indiana' 'Iowa'...
'Kansas' 'Kentucky' 'Louisiana' 'Maine' 'Maryland'...
'Massachusetts' 'Michigan' 'Minnesota' 'Mississippi' 'Missouri'...
'Montana' 'Nevada' 'Nebraska' 'New Hampshire' 'New Jersey'...
'New Mexico' 'New York' 'North Carolina' 'North Dakota' 'Ohio'...
'Oklahoma' 'Oregon' 'Pennsylvania' 'Rhode Island' 'South Carolina'...
'South Dakota' 'Tennessee' 'Texas' 'Utah' 'Vermont'...
'Virginia' 'Washington' 'West Virginia' 'Wisconsin' 'Wyoming'};
count = nan(1,50);
test = 'Wisconsin is better than California... or is California worse?';
for i = 1:50
count(i) = length(strfind(test,states{i}));
end
bar(1:50,count)
set(gca,'xticklabel',states)
xtickangle(75)
The figure this code produces is this:
I want the second bar to be aligned with Wisconsin. It seems that the state labels are being placed on every 5th value; Wisconsin is 48, and the tick "Hawaii" is near is 50. Please help me figure out the state names are not assigned on each single value. Again, I'm hoping to see all 50 state names on the x-axis.

回答 (1 件)

Rik
Rik 2021 年 2 月 19 日
You need to set the location of the xticks as well, otherwise Matlab will use the current xticks and use your provided labels instead of the default labels.
states = {'Alabama' 'Alaska' 'Arizona' 'Arkansas' 'California'...
'Colorado' 'Connecticut' 'Delaware' 'Florida' 'Georgia'...
'Hawaii' 'Idaho' 'Illinois' 'Indiana' 'Iowa'...
'Kansas' 'Kentucky' 'Louisiana' 'Maine' 'Maryland'...
'Massachusetts' 'Michigan' 'Minnesota' 'Mississippi' 'Missouri'...
'Montana' 'Nevada' 'Nebraska' 'New Hampshire' 'New Jersey'...
'New Mexico' 'New York' 'North Carolina' 'North Dakota' 'Ohio'...
'Oklahoma' 'Oregon' 'Pennsylvania' 'Rhode Island' 'South Carolina'...
'South Dakota' 'Tennessee' 'Texas' 'Utah' 'Vermont'...
'Virginia' 'Washington' 'West Virginia' 'Wisconsin' 'Wyoming'};
count = nan(1,50);
test = 'Wisconsin is better than California... or is California worse?';
for i = 1:50
count(i) = length(strfind(test,states{i}));
end
bar(1:50,count)
set(gca,'xticklabel',states,'xtick',1:numel(states))
xtickangle(75)

タグ

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by