matplotlib - plotting two histograms in same axes with overlapping x/y ticks

Viewed 1152

I'm trying to plot histograms in multiple axes of my plot. My script below is doing that, but I simply can't standardize the x/y ticks for each ax i.e. with no overlapping, a common interval range for each ax.

I wanna specify the x/y ticks for each ax instead of setting global ticks for the whole plot.

The output I have so far is below, too. As you can see the ticks are messed up, specially in the last ax. I've tried ax_set_x/yticks, plt.x/yticks.... but I'm pretty sure there is something I'm doing wrong. Thanks a lot!! enter image description here

The script:

import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss

data = np.random.normal(0.0005, 0.001,1000)
data2 = np.random.normal(0.0004, 0.001,1000)-data
diff = {k:[data, data2] for k in range(3)}
for k in diff:
    print k
ttls= ['SC2 vs SC1', 'SC4 vs SC3','SC6 vs SC5']
colors = ['chocolate', 'green']
leg = ['var1', 'var2'] 
bins = 100
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(8.27, 11.69))
fig.add_subplot(111, frameon=False)
fig.suptitle('Normed Histograms', color='#6E6E6E', fontsize=10, fontweight='bold')
for ax, ttl, arr in zip(axes, ttls, diff.itervalues()):
    ax.hist((arr[0], arr[1]),bins, histtype='stepfilled', density=True, color=colors, label=leg, alpha=0.70)
    for i, v in enumerate(arr):
        mean = np.mean(v) 
        std = np.std(v)    
        xRange = np.linspace(np.min(v), np.max(v))#, len(cs))
        nd = ss.norm.pdf(xRange, mean, std)
        if  i == 0:
            socNd = ax.plot(xRange, nd, color='r', alpha=0.70, linewidth=0.8, label="fitted PDF*")
            socLine = ax.axvline(mean, color=colors[0], linestyle = ':',linewidth=2, label="Mean value")
        if i == 1:
            bcNd = ax.plot(xRange, nd, color='r', alpha=0.70, linewidth=0.8)
            bcLine = ax.axvline(mean, color=colors[1], linestyle = ':',linewidth=2)                 
    ax.set_title(ttl, loc='left', color='#6E6E6E', fontsize=8.5, fontweight='bold', pad=12)
    ax.set_ylabel("Frequency",  color='#6E6E6E', fontsize=8) 
    axes[2].legend(loc='lower center', bbox_to_anchor=(0.5, -0.5),ncol=4)
    axes[2].set_xlabel("xlabel", fontsize=8, labelpad=3)
plt.subplots_adjust(hspace=0.7)

plt.show()
1 Answers

You are creating you 3 subplots using fig, axes = plt.subplots(...) you are then creating another subplot on top of your existing 3. However because you have set frameon=False only the tick and tick labels are shown (try removing the frameon=False and you will see the problem).

The solution is to simply remove fig.add_subplot(111, frameon=False) so that you are not creating an extra set of axes.

The resulting graph for me looks like:

enter image description here

Related