首页 > 解决方案 > matplotlib:使用样式“fivethirtyeight”时,如何在条形图和图例后面绘制网格线

问题描述

作为标题,当使用“fivethirtyeight”等样式时,如何将网格线移到后面?

我试过 Axis.set_axisbelow(True)and ax.grid(zorder=0) ,但它们都不起作用。

图在这里显示

如您所见,网格线位于图例之上,难以阅读。

代码如下所示:

import pandas as pd

import matplotlib.pyplot as plt



plt.style.use('fivethirtyeight')



data = pd.DataFrame(np.array([['Bacterial alpha-amylase', 1.0, 4.0, 0.0, 4.0] ,
['Fungal glucoamylase', 7.5, 24.0, 0.0, 24.0] ,
['Fungal phytase', 2.2, 6.0, 0.0, 6.0] ,
['Bacterial protease', 4.3, 14.0, 0.0, 14.0] ,
['Bacterial amylase', 10.2, 29.0, 0.0, 29.0] ,
['GSK_A', 12.0, 65.0, 0.0, 65.0] ,
['GSK_B', 3.0, 25.0, 0.0, 25.0] ,
['GSK_C', 4.0, 35.0, 0.0, 35.0] ,
['Ecoinvent_Europe', 6.4237, 0.052362, 0.0, 0.052362] ,
['Ecoinvent_rest of world', 8.8557, 0.056691, 0.0, 0.056691] ,
['Rhodium', 34967.0, 587.81, 587.81, 0.0]]), 
columns = ['enzyme', 'GWP100', 'Acidification', 'new_acid_2', 'new_acid_1'])

# the one below is to convert my numbers to float,
# which is set as string by default in the first place by python

for i in data.columns.values:
    if i =='enzyme':
        pass
    else:
        data[i] = data[i].astype(float)




fig = plt.figure(2, figsize=(6,4))


ax3 = fig.add_subplot(111)
ax4 = ax3.twinx()

data['new_acid_2'] = data.Acidification
data.loc[data['new_acid_2']<100, 'new_acid_2'] = 0

data['new_acid_1'] = data.Acidification
data.loc[data['new_acid_1'] > 100, 'new_acid_1'] = 0


my_label = data.enzyme.values


x_pos = np.arange(11)


h1 = ax3.bar(x_pos, data.new_acid_1.values,  label=my_label)
h2 = ax4.bar(x_pos, data.new_acid_2.values,  label=my_label)
h1[-1].set_color('maroon')
h2[-1].set_color('maroon')


ax3.legend(h2,my_label, loc = 2,fontsize = 8)
ax3.set_axisbelow(True)


plt.show()

使用“fivethirtyeight”等样式时,如何将网格线移到后面?

任何建议表示赞赏。提前致谢。

标签: pythonmatplotliblegendgridlines

解决方案


不显示双轴网格线是有意义的,因为它会使ax3间距看起来不均匀。h1绘图后添加以下两行h2

ax3.grid(zorder=0)
ax4.grid(False)

替代解决方案是zorder=1在绘制条形图时使用。条形的zorder数量应大于网格的数量(默认为 0)。将zorder视为二维画布/图形的深度,您可以看到深度进入纸张/屏幕的位置。

h1 = ax3.bar(x_pos, data.new_acid_1.values,  label=my_label,zorder=1)
h2 = ax4.bar(x_pos, data.new_acid_2.values,  label=my_label, zorder=1)
ax3.grid(True)
ax4.grid(False)

输出

在此处输入图像描述


推荐阅读