Matplotlib: grid lines above bars

This is simple code that reproduces the type of chart that it is trying to build:

import matplotlib.pyplot as plt
import seaborn as sb
import numpy as np

x  = np.arange(1,11)
y1 = x[::-1]
y2 = 2 ** x

fig  = plt.figure(figsize = (8,6))
ax1 = fig.add_subplot(111)
plt.bar(x, y1, 1, color = 'blue')
ax1.grid(axis = 'y')
ax2 = ax1.twinx()
ax2.plot(x+0.5, y2, color = 'red')

What produces:

enter image description here

Grid lines in the last section of the line appear above the stripes. How can I put them in jail?

+4
source share
2 answers
import matplotlib.pyplot as plt
import numpy as np

x  = np.arange(1,11)
y1 = x[::-1]
y2 = 2 ** x

fig  = plt.figure(figsize = (8,6))
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

# from back to front
ax1.grid(axis="both", color="black")
ax1.bar(x, y1, 1, alpha=.9, edgecolor="black", facecolor='blue', zorder=1)

ax2.grid(axis="y", color="green")
#ax2.grid(False)
ax2.plot(x+0.5, y2, color='red')

plt.show()

which produce the graph below illustrating the zorder elements.

ax1.grid => ax1.bar => ax2.grid => ax2.line

zorder elements in the plot

The only workaround I can think of is to build a grid in ax1 and turn off the grid of ax2 (if you really want to build a horizontal grid line for ax2, then you may have to build a line with ax1.

ax1.grid(True, axis="both", color="yellow")
ax1.bar(x, y1, 1, alpha=.9, edgecolor="black", facecolor='blue', zorder=1)

ax2.grid(False)
ax2.plot(x+0.5, y2, color='red')

some workaround

0
source

, , . , , , , .

this, , ( , , ).

import matplotlib.pyplot as plt
import seaborn as sb
import numpy as np

x  = np.arange(1,11)
y1 = x[::-1]
y2 = 2 ** x

fig  = plt.figure(figsize = (8,6))
ax1 = fig.add_subplot(111)
plt.bar(x, y1, 1, color = 'blue')
ax2 = ax1.twinx()
ax2.plot(x+0.5, y2, color = 'red')
ax2.set_yticks(np.linspace(ax2.get_yticks()[0],ax2.get_yticks()[-1],len(ax1.get_yticks())))

enter image description here

. , , , : ax2.grid(False) .

enter image description here

: , . ( ) . , - , .

0

Source: https://habr.com/ru/post/1668651/


All Articles