The histogram2
function (added in R2015b) has the DisplayStyle
optional argument, which controls whether the output is displayed using "bars" (of uniform color but different height) or "tiles" (with the same height of 0, but with different colors), as demonstrated below:
rng(1337); X = rand(100,1)-0.5; Y = randn(100,1); rng('default');
figure();
subplot(1,2,1); hH(1) = histogram2(X, Y, 'DisplayStyle', 'bar3');
subplot(1,2,2); hH(2) = histogram2(X, Y, 'DisplayStyle', 'tile');
I would like to combine the two modes, to get bars with different height which also have different colors. As mentioned, I tried using the 'DisplayStyle'
option, but it changes too many visual elements at the same time. Can anybody suggest a way to get what I want?
I'd very much like the solution to be a histogram2
object (as opposed to e.g. bar3
), as these are much more convenient to work with later on.
histogram2(X, Y, 'FaceColor', 'flat');
Those preferring a "brute force" method over thoroughly reading documentation might approach this problem by comparing the two resulting objects (hH(1)
, hH(2)
) in depth, finding the different properties, then attempting to assign the desired values from the other style. Indeed, these differences appear:
FaceColor
: 'auto'
vs. 'flat'
, in the "blue" and "flat" charts, respectively.FaceLighting
: 'lit'
vs. 'none'
, in the "blue" and "flat" charts, respectively.Then, fortunately, the following line indeed works:
hH(1).FaceColor = 'flat';
The reason this works is found in the documentation of FaceColor
:
Histogram bar color, specified as one of these values:
'none'
— ....
'flat'
— Bar colors vary with height. Bars with different height have different colors. The colors are selected from the figure or axes colormap.
'auto'
— ....
... the reading of which earlier could've saved some time.
When extensive documentation is available1, we shouldn't just stop at the first thing that seems related to out problem, because an obvious solution may appear just a little further down.
1 The case with the majority of MATLAB functions, and especially true for MATLAB's graphic objects.