Bar graph labels not aligning with index value

13 次查看(过去 30 天)
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)

类别

Help CenterFile Exchange 中查找有关 Particle & Nuclear Physics 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by