XTick labels for bar plot of 2 data sets
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Star Strider
2019-1-30
编辑:Star Strider
2019-1-30
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 个评论
Star Strider
2019-1-30
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.
更多回答(1 个)
Ollie A
2019-1-30
编辑:Ollie A
2019-1-30
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Bar Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!