python - Two bar charts in matplotlib overlapping the wrong way -



python - Two bar charts in matplotlib overlapping the wrong way -

i'm creating bar plot matplotlib in python, , i'm having bit of problem overlapping bars:

import numpy np import matplotlib.pyplot plt = range(1,10) b = range(4,13) ind = np.arange(len(a)) width = 0.65 fig = plt.figure() ax = fig.add_subplot(111) ax.bar(ind+width, a, width, color='#b0c4de') ax2 = ax.twinx() ax2.bar(ind+width+0.35, b, 0.45, color='#deb0b0') ax.set_xticks(ind+width+(width/2)) ax.set_xticklabels(a) plt.tight_layout()

i want bluish bars in front, not reddish ones. way have managed so far switch ax , ax2, ylabels going reversed well, don't want. isn't there simple way tell matplotlib render ax2 before ax?

in addition, ylabels on right beingness cutting off plt.tight_layout(). there way avoid while still using tight_layout?

perhaps there improve way not know about; however, can swap ax , ax2 , swap location of corresponding y-ticks with

ax.yaxis.set_ticks_position("right") ax2.yaxis.set_ticks_position("left") import numpy np import matplotlib.pyplot plt = range(1,10) b = range(4,13) ind = np.arange(len(a)) width = 0.65 fig = plt.figure() ax = fig.add_subplot(111) ax.bar(ind+width+0.35, b, 0.45, color='#deb0b0') ax2 = ax.twinx() ax2.bar(ind+width, a, width, color='#b0c4de') ax.set_xticks(ind+width+(width/2)) ax.set_xticklabels(a) ax.yaxis.set_ticks_position("right") ax2.yaxis.set_ticks_position("left") plt.tight_layout() plt.show()

by way, instead of doing math yourself, can center bars using align='center' parameter:

import numpy np import matplotlib.pyplot plt = range(1,10) b = range(4,13) ind = np.arange(len(a)) fig = plt.figure() ax = fig.add_subplot(111) ax.bar(ind+0.25, b, 0.45, color='#deb0b0', align='center') ax2 = ax.twinx() ax2.bar(ind, a, 0.65, color='#b0c4de', align='center') plt.xticks(ind, a) ax.yaxis.set_ticks_position("right") ax2.yaxis.set_ticks_position("left") plt.tight_layout() plt.show()

(the result same above.)

python matplotlib bar-chart overlapping

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -