简体   繁体   中英

Pandas bar plot with secondary y-axis: hide grid line below plot

I am plotting some data as described in the pandas documentation .

import pandas as pd
import matplotlib.pyplot as plt


d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)


# plot
ax = df.plot(kind='bar', secondary_y=['col1'])
ax.set_ylabel('Foo')
ax.right_ax.set_ylabel('Bar')

# does not show any effect
ax.grid(True, zorder=0)
ax.right_ax.grid(True, zorder=0)

# does not show any effect
ax.set_axisbelow(True)
# works
ax.right_ax.set_axisbelow(True)

plt.show()

which yields

在此处输入图片说明

Now my problem is that I want to hide the grid lines behind the bars. I have already tried different combinations of zorder and set_axisbelow but this only works for the "first" bars.

How can I hide the grid (and possibly also the legend) behind the bars?

Thanks in advance!

Only enable the grid for the lower axes.

import pandas as pd
import matplotlib.pyplot as plt

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

# plot
ax = df.plot(kind='bar', secondary_y=['col1'])
ax.set_ylabel('Foo')
ax.right_ax.set_ylabel('Bar')

ax.grid(True)
ax.set_axisbelow(True)

plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM