XTick labels for bar plot of 2 data sets
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
VB ABQ
el 30 de En. de 2019
Comentada: Star Strider
el 30 de En. de 2019
I want to make a bar chart with 2 data sets that have different number of values and I want each set to have the same color. Example code:
figure, bar([1:5],rand(1,5),'b'); hold on
bar([6:12],rand(1,7),'r')
The bar chart shows the XTickLabels for the first data set but not the second. How do I get XTickLabels for all 12 bars?
If I make a bar chart with a dataset with 12 entries, I can't change the colors of some bars, for example bars 1 - 5, so I had to break it up and make 2 bar plots.
Hope this makes sense.
Thanks!
0 comentarios
Respuesta aceptada
Star Strider
el 30 de En. de 2019
Editada: Star Strider
el 30 de En. de 2019
One way is to concatanate the 'XData' vectors of both series, and use that as the 'XData' value for the first (blue) bar series, then plot both series:
figure
hb1 = bar([1:5],rand(1,5),'b');
hb1.XData = 1:12;
hold on
hb2 = bar([6:12],rand(1,7),'r');
hold off
This also works even if the 'XData' vectors are not continuous:
figure
hb1 = bar([1:5],rand(1,5),'b');
hb1.XData = [1:5 7:13];
hold on
hb2 = bar([7:13],rand(1,7),'r');
hold off
EDIT —
Added plot:
3 comentarios
Star Strider
el 30 de En. de 2019
As always, my pleasure!
Apparently it’s necessaary to extend the 'XData' range for the first (blue) series in order for the second (red) series to plot correctly. I experimented with a number of different approaches before I discovered this one, including setting the 'XData' property of either ‘hb1’ or ‘hb2’ to concatanate both after plotting the second (red) bar series, and I also experimented with using yyaxis. The method I posted is the only way I could get it to work.
I don’t know if this is the way bar is designed to work, or if it’s a bug. I would like to have bar (or perhaps a second version of bar, named something slightly different) to work seamlessly with the second series without having to create a work-around.
If you do a lot of these, it would be worthwhile for you to create your own function to do this sort of plot, by concatenating the 'XData' vectors (or what would become the 'XData' vectors) in the correct order, and then doing the bar plot with them.
Más respuestas (1)
Ollie A
el 30 de En. de 2019
Editada: Ollie A
el 30 de En. de 2019
You can modify the colour of individual bars in the bar chart using CData.
This documentation explains it well:
Here is an example of how you could implement it:
b = bar([rand(1,5),rand(1,7)]); % Create bar chart.
b.FaceColor = 'flat';
b.CData(6:end,:) = repmat([1 0 0],7,1); % Choose bars to change colour to red.
Ver también
Categorías
Más información sobre Bar Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!