Two histograms in matplotlib overlap the wrong path

I am creating a hatch plot with matplotlib in Python and I have a problem with overlapping stripes:

import numpy as np
import matplotlib.pyplot as plt

a = 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()

Barplot

I want the blue stripes to be in front, not the red ones. The only thing I have managed to do so far is to switch ax and ax2, but then the needles will also be canceled, which I do not want. Is there a simple way to tell matplotlib to render ax2 before ax?

In addition, plt.tight_layout () is clipped to the ylabels on the right. Is there a way to avoid this when using the tight_layout function?

+5
source share
1 answer

, , ; ax ax2, y

ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")

import numpy as np
import matplotlib.pyplot as plt

a = 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()

enter image description here


, , , align='center':

import numpy as np
import matplotlib.pyplot as plt

a = 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()

( , ).

+6

All Articles