Bar graph labels not aligning with index value

14 vues (au cours des 30 derniers jours)
Sam Acker
Sam Acker le 18 Fév 2021
Réponse apportée : Rik le 19 Fév 2021
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.

Réponses (1)

Rik
Rik le 19 Fév 2021
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)

Catégories

En savoir plus sur Particle & Nuclear Physics dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by