Matplotlib:在图形后面保留网格线,但上面的y和x轴

luk*_*_16 11 python plot matplotlib

我很难在我的图形下绘制网格线而不会弄乱主x轴和y轴zorder:

import matplotlib.pyplot as plt
import numpy as np


N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd, alpha=0.9, linewidth = 0,zorder=3)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd, alpha=0.9, linewidth = 0,zorder=3)

# add some
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

fig.gca().yaxis.grid(True, which='major', linestyle='-', color='#D9D9D9',zorder=2, alpha = .9)
[line.set_zorder(4) for line in ax.lines]

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()
Run Code Online (Sandbox Code Playgroud)

这个例子来自matplotlib自己的,我稍微调整了一下,以展示如何使问题出现.我无法发布图像,但是如果运行代码,您将看到条形图绘制在水平网格线上方以及x和y轴上方.我不希望图形隐藏x和y轴,特别是当刻度线也被阻挡时.

Fra*_*ano 6

我尝试过 matplotlib 1.2.1、1.3.1rc2 和 master (提交 06d014469fc5c79504a1b40e7d45bc33acc00773)

要将轴脊置于条形顶部,您可以执行以下操作:

for k, spine in ax.spines.items():  #ax.spines is a dictionary
    spine.set_zorder(10)
Run Code Online (Sandbox Code Playgroud)

编辑

看来我无法使刻度线位于条形顶部。我试过了

1. ax.tick_params(direction='in', length=10, color='k', zorder=10)
   #This increases the size of the lines to 10 points, 
   #but the lines stays hidden behind  the bars
2. for l in ax.yaxis.get_ticklines():
       l.set_zorder(10)
Run Code Online (Sandbox Code Playgroud)

以及其他一些没有结果的方式。似乎在绘制条形时,它们被放在顶部并且 zorder 被忽略

解决方法可能是将刻度线向外绘制

ax.tick_params(direction='out', length=4, color='k', zorder=10)
Run Code Online (Sandbox Code Playgroud)

或同时向内和向外,使用direction='inout'

编辑2

我在 @tcaswell 评论后做了一些测试。

如果函数zorderax.bar设置为 <=2,则轴、刻度线网格线将绘制在条形上方。如果值 >2.01(轴的默认值),则会在轴、刻度线和网格的顶部绘制条形。然后可以为脊柱设置更大的值(如上所述),但任何更改zorder刻度线的尝试都会被忽略(尽管这些值在相应的艺术家上更新)。

我尝试过将 和 用作zorder=1网格barzorder=0并且网格绘制条形的顶部。所以 zorder 被忽略。

回顾

在我看来,刻度线和网格zorder只是被忽略并保留为默认值。对我来说,这是一个与bar或某些相关的错误patches

顺便说一句,我记得在使用时成功更改了刻度线中的 zorderimshow


ned*_*dim 6

当我在后台有网格线时,我遇到了在绘图线下方绘制轴的问题:

ax.yaxis.grid()  # grid lines
ax.set_axisbelow(True)  # grid lines are behind the rest
Run Code Online (Sandbox Code Playgroud)

对我有用的解决方案是zorderplot()函数的参数设置为1到2之间的值.它不是立即清楚,但是zorder值可以是任何数字.从matplotlib.artist.Artist课程文档:

set_zorder(水平)

设置艺术家的zorder.首先绘制具有较低zorder值的艺术家.

ACCEPTS:任何数字

因此:

for i in range(5):
    ax.plot(range(10), np.random.randint(10, size=10), zorder=i / 100.0 + 1)
Run Code Online (Sandbox Code Playgroud)

我没有检查过这个范围之外的值,也许它们也可以工作.