Repository: rootpy/rootpy

Issue:
Transparency (alpha) not working for root2matplotlib
Dear all,

Since the latest rootpy update (a bunch of commits since last git pull) I am no longer able to make transparent histograms. The example is the rootpy one but with 'alpha = 0.5' set:

``` python
#!/usr/bin/env python
import numpy as np
from rootpy.plotting import Hist, HistStack
import rootpy.plotting.root2matplotlib as rplt
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
import ROOT
# Setting this to True (default in rootpy)
# changes how the histograms look in ROOT...
ROOT.TH1.SetDefaultSumw2(False)
ROOT.gROOT.SetBatch(True)

# create normal distributions
mu1, mu2, sigma1, sigma2 = 100, 140, 15, 5
x1 = mu1 + sigma1 * np.random.randn(10000)
x2 = mu2 + sigma2 * np.random.randn(1000)
x1_obs = mu1 + sigma1 * np.random.randn(10000)
x2_obs = mu2 + sigma2 * np.random.randn(1000)

# create histograms
h1 = Hist(100, 40, 200, title='Background')
h2 = h1.Clone(title='Signal')
h3 = h1.Clone(title='Data')
h3.markersize=1.2

# fill the histograms with our distributions
map(h1.Fill, x1)
map(h2.Fill, x2)
map(h3.Fill, x1_obs)
map(h3.Fill, x2_obs)

# set visual attributes
h1.fillstyle = 'solid'
h1.fillcolor = 'green'
h1.linecolor = 'green'
h1.linewidth = 0
h1.legendstyle = 'F'

h2.fillstyle = 'solid'
h2.fillcolor = 'red'
h2.linecolor = 'red'
h2.linewidth = 0
h2.legendstyle = 'F'

stack = HistStack()
stack.Add(h1)
stack.Add(h2)

# plot with matplotlib
fig = plt.figure(figsize=(7, 5), dpi=100)#, facecolor='white')
axes = plt.axes()
axes.xaxis.set_minor_locator(AutoMinorLocator())
axes.yaxis.set_minor_locator(AutoMinorLocator())
axes.tick_params(which='major', labelsize=15, length=8)
axes.tick_params(which='minor', length=4)
rplt.errorbar(h3, xerr=False, emptybins=False, axes=axes, zorder = 4)
rplt.hist(stack, stacked=True, axes=axes, alpha = 0.5, zorder =2)
plt.xlabel('Mass', position=(1., 0.), ha='right')
plt.ylabel('Events', position=(0., 1.), va='top')
plt.legend(numpoints=1)
plt.tight_layout()
plt.savefig('plots/matplotlib_hist.png')
```

This produces
![matplotlib_hist](https://f.cloud.github.com/assets/1213276/2217754/24917ce0-9a22-11e3-9980-4694dd2323c8.png)

As you can see the legend filling is correct, but the histograms themselves are not.

To test if it is a matplotlib bug, I've also tested this small example in the same environment:

``` python
import random
import numpy
from matplotlib import pyplot

x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]

bins = numpy.linspace(-10, 10, 100)

pyplot.hist(x, bins, alpha=0.5)
pyplot.hist(y, bins, alpha=0.5)
pyplot.show()
```

which works well:
![test2](https://f.cloud.github.com/assets/1213276/2217793/658ce202-9a22-11e3-96d7-22b7a91c2e96.png)

Could you please have a look?



Discussion:
Thanks for reporting! Fixing this now....


Resolving patch:
diff --git a/rootpy/plotting/root2matplotlib.py b/rootpy/plotting/root2matplotlib.py
--- a/rootpy/plotting/root2matplotlib.py
+++ b/rootpy/plotting/root2matplotlib.py
@@ -43,36 +43,37 @@
 ]
 
 
-def _set_defaults(h, kwargs, types=['common']):
+def _set_defaults(obj, kwargs, types=['common']):
     defaults = {}
     for key in types:
         if key == 'common':
-            defaults['label'] = h.GetTitle()
-            defaults['visible'] = h.visible
+            defaults['label'] = obj.GetTitle()
+            defaults['visible'] = getattr(obj, 'visible', True)
+            defaults['alpha'] = getattr(obj, 'alpha', None)
         elif key == 'line':
-            defaults['linestyle'] = h.GetLineStyle('mpl')
-            defaults['linewidth'] = h.GetLineWidth()
+            defaults['linestyle'] = obj.GetLineStyle('mpl')
+            defaults['linewidth'] = obj.GetLineWidth()
         elif key == 'fill':
-            defaults['edgecolor'] = h.GetLineColor('mpl')
-            defaults['facecolor'] = h.GetFillColor('mpl')
-            root_fillstyle = h.GetFillStyle('root')
+            defaults['edgecolor'] = obj.GetLineColor('mpl')
+            defaults['facecolor'] = obj.GetFillColor('mpl')
+            root_fillstyle = obj.GetFillStyle('root')
             if root_fillstyle == 0:
                 defaults['facecolor'] = 'none'
                 defaults['fill'] = False
             elif root_fillstyle == 1001:
                 defaults['fill'] = True
             else:
-                defaults['hatch'] = h.GetFillStyle('mpl')
+                defaults['hatch'] = obj.GetFillStyle('mpl')
                 defaults['facecolor'] = 'none'
         elif key == 'marker':
-            defaults['marker'] = h.GetMarkerStyle('mpl')
-            defaults['markersize'] = h.GetMarkerSize() * 5
-            defaults['markeredgecolor'] = h.GetMarkerColor('mpl')
-            defaults['markerfacecolor'] = h.GetMarkerColor('mpl')
+            defaults['marker'] = obj.GetMarkerStyle('mpl')
+            defaults['markersize'] = obj.GetMarkerSize() * 5
+            defaults['markeredgecolor'] = obj.GetMarkerColor('mpl')
+            defaults['markerfacecolor'] = obj.GetMarkerColor('mpl')
         elif key == 'errors':
-            defaults['ecolor'] = h.GetLineColor('mpl')
+            defaults['ecolor'] = obj.GetLineColor('mpl')
         elif key == 'errorbar':
-            defaults['fmt'] = h.GetMarkerStyle('mpl')
+            defaults['fmt'] = obj.GetMarkerStyle('mpl')
     for key, value in defaults.items():
         if key not in kwargs:
             kwargs[key] = value
@@ -232,6 +233,7 @@ def hist(hists,
             else:
                 low = sum(hists[i + 1:])
             high = h + low
+            high.alpha = getattr(h, 'alpha', None)
             proxy = _hist(high, bottom=low, axes=axes, logy=logy, **kwargs)
             returns.append(proxy)
         if not reverse:
@@ -276,18 +278,23 @@ def _hist(h, axes=None, bottom=None, logy=None, zorder=None, **kwargs):
         fill_between(bottom, h, axes=axes, logy=logy, linewidth=0,
                      facecolor=kwargs['facecolor'],
                      edgecolor=kwargs['edgecolor'],
-                     hatch=kwargs.get('hatch', None),
+                     hatch=kwargs['hatch'],
+                     alpha=kwargs['alpha'],
                      zorder=zorder)
     # draw the edge
-    step(h, axes=axes, logy=logy, label=None, zorder=zorder + 1)
-    if h.legendstyle.upper() == 'F':
+    step(h, axes=axes, logy=logy, label=None,
+         zorder=zorder + 1, alpha=kwargs['alpha'])
+    # draw the legend proxy
+    if getattr(h, 'legendstyle', '').upper() == 'F':
         proxy = plt.Rectangle((0, 0), 0, 0, **kwargs_proxy)
         axes.add_patch(proxy)
     else:
+        # be sure the linewidth is greater than zero...
         proxy = plt.Line2D((0, 0), (0, 0),
                            linestyle=kwargs_proxy['linestyle'],
                            linewidth=kwargs_proxy['linewidth'],
                            color=kwargs_proxy['edgecolor'],
+                           alpha=kwargs['alpha'],
                            label=kwargs_proxy['label'])
         axes.add_line(proxy)
     return proxy


Test patch: