python - 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”等样式时,如何将网格线移到后面?
任何建议表示赞赏。提前致谢。
解决方案
不显示双轴网格线是有意义的,因为它会使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)
输出
推荐阅读
- mysql - 竞态条件下的 INSERT-SELECT 和 UPDATE
- python - 从熊猫系列中去除非空白字符
- neural-network - 在没有历史数据的情况下训练神经网络
- grub2 - 如何使用带有 UEFI 的 GRUB2 来安全启动 Ubuntu?
- php - PHP QR Code 不会显示 UTF-8 字符
- arrays - 重击。初始化动态关联数组
- matlab - 设置 MATLAB 的默认图形大小
- c - 写入文件的完整位置时出现分段错误
- php - 是否有更短、更优化的方法来检查 GET 参数?
- angular - Angular 6 Reactive Forms 动态复选框