'Octave: Creating Two Histograms with Color Blending

I am creating one histogram on top of another in Octave.

    hold on;
    hist(normalData(:, column), 10, 1, "facecolor", "g");
    hist(anomalousData(:, column), 10, 1, "facecolor", "r");
    hold off;

enter image description here

As you can see there is overlap and the red data obscures some of the green data. Is there a way around this? Perhaps by having the colors blend on the overlapping portions?



Solution 1:[1]

There is a long way around your problem. Unfortunately the plotting property for transparency "facealpha" does not work with the hist() function.

The code below shows my work around. The default graphics toolkit may be fltk, so change it to gnuplot.

clear all

graphics_toolkit("gnuplot")

A = randn(1000,1);
B = randn(1000,1)+2;

Still use hist to calculate the distributions

[y1 x1] = hist(A,10);
[y2 x2] = hist(B,10);

Now we are going to convert the hist data into a format for plotting that will allow transparency.

[ys1 xs1] = stairs(y1, x1);
[ys2 xs2] = stairs(y2, x2);

xs1 = [xs1(1); xs1; xs1(end)];  xs2 = [xs2(1); xs2; xs2(end)];
ys1 = [0; ys1; 0];  ys2 = [0; ys2; 0];

Plot the data with the fill function

clf
hold on; 
h1=fill(xs1,ys1,"red");
h2=fill(xs2,ys2,"green");

Change the transparency to the desired level.

set(h1,'facealpha',0.5);
set(h2,'facealpha',0.5);
hold off;

I'd post an image if I had more reputation.

Solution 2:[2]

This is still the first result when searching for transparent histograms, so I thought I would clarify things. Osvaldo's answer is correct, although he doesn't show the correct setting (facealpha). Previously it was necessary to use gnuplot to get transparency, but I didn't find this necessary (Octave 6.2.0 x86_64-w64-mingw32), and in fact I found gnuplot took forever to load the plot.

To change the histogram transparency, you just need to access the patch objects and set their facealpha property to something like 0.5.

% Plot data
hist(data1,20,'facecolor',[0.9,0.9,0.9]);
hold on;
hist(data2,20,'facecolor',[0.9,0.7,0.7]);

% Get patch objects for each histogram
h = findobj(gca,'Type','patch');

% Set facealpha
set(h(1),'facealpha',0.5);
set(h(2),'facealpha',0.5);

Plot showing semitransparent and overlapping histograms

Solution 3:[3]

I´ve found in the web a very simple way to do this (it´s not mine, and I don´t really know if this is allowed), the webpage is this

https://chi3x10.wordpress.com/2008/03/10/histograms-of-two-set-of-data-with-different-color-in-matlab/

the code is this

 hist(data1);
 hold on;
 hist(data2);
 hist(data3);
h = findobj(gca,’Type’,’patch’);
display(h)

set(h(1),’FaceColor’,’r’,’EdgeColor’,’k’);
set(h(2),’FaceColor’,’g’,’EdgeColor’,’k’);
set(h(2),’FaceColor’,’b’,’EdgeColor’,’k’);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sam Gallagher
Solution 3 Osvaldo