使用 matplotlib 格式化为一组条形图

formatting to group of bars using matplotlib

我正在努力学习python主要是为了绘图。这是我的示例代码:

import numpy as np
import matplotlib.pyplot as plt


a=[[1,2,3,4],[2,3,4,5],[3,4,5,6]]
x=np.arange(len(a[0]))
width=0.2

fig, ax = plt.subplots(figsize=(8,6))
patterns=['/','\','*']

for bar in a:
    ax.bar(x,bar,width,edgecolor='black',color='lightgray', hatch=patterns.pop(0))
    x=x+width

plt.show()

现在的问题是,我需要所有条形的 black 边缘颜色以及给定的 hatch patter。但是,格式仅适用于第一组条形图。这是我的输出。 (我正在使用 python3)。

这里缺少什么或出了什么问题?我环顾四周,但没有找到任何修复方法。

更新: 我尝试了不同的选项:python2、python3 和 pdf/png。这是结果

我也试过 'backend' 作为 matplotlib.use('Agg')。我已经更新了我的 matplotlib 版本 (2.1.0)。

edgecolor 元组的 alpha 值看起来有问题。设置为 1 即可解决问题。

有一个current issue in matplotlib 2.1 that only the first bar's edgecolor is applied. The same for the hatch, see this issue. Also see

您可能在 python3 中使用 matplotlib 2.1,但在 python2 中未使用,因此在 python2 中它适合您。如果我 运行 你在 python 2 中使用 matplotlib 2.1 的代码,我会得到同样的不良行为。

一旦 matplotlib 2.1.1 发布,该问题将得到解决。

与此同时,解决方法是在各个条上设置边缘颜色和阴影线:

import numpy as np
import matplotlib.pyplot as plt


a=[[1,2,3,4],[2,3,4,5],[3,4,5,6]]
x=np.arange(len(a[0]))
width=0.2

fig, ax = plt.subplots(figsize=(8,6))
patterns=['/','\','*']

for y in a:
    bars = ax.bar(x,y,width,color='lightgray')
    hatch= patterns.pop(0)
    for bar in bars:
        bar.set_edgecolor("black")
        bar.set_hatch(hatch)
    x=x+width

plt.show()