matplotlib:使用样式“ fivethirtyeight”时,如何在条和图例后面绘制网格线

时间:2018-09-23 09:31:44

标签: python matplotlib legend gridlines

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

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

The figure is shown here

如您所见,网格线位于图例的顶部,难以阅读。

代码显示在这里:

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”等样式时如何将网格线向后移动?

任何建议表示赞赏。预先感谢。

1 个答案:

答案 0 :(得分:1)

不显示双轴网格线是有意义的,因为这会使ax3间距看起来不均匀。在绘制h1h2

之后添加以下两行
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)

输出

enter image description here