如何在matplotlib 2.0中填充仅具有填充(无背景颜色)的区域

时间:2017-01-30 05:39:29

标签: python python-2.7 matplotlib plot

最近对matplotlib fill_betweenhatchsee links here)的更新,填充区域不再像以前那样表现。也就是说,该区域要么填充颜色,要么阴影是黑色的,或者区域没有填充颜色,并且阴影不可见。

以下是来自相同代码(from this answer)的图表的并排比较

import matplotlib.pyplot as plt
import matplotlib as mpl
plt.plot([0,1],[0,1],ls="--",c="b")
plt.fill_between([0,1],[0,1], color="none", hatch="X", edgecolor="b", linewidth=0.0)
plt.show()

enter image description here

有没有办法在2.X中重现1.X图?我对后端完全不熟悉,但mpl.rcParams['hatch.color'] = 'b'并且关键字color, edgecolor的变体并没有帮助。

提前感谢您帮助澄清这一点。

2 个答案:

答案 0 :(得分:11)

matplotlib> 2.0.1

由于GitHub上有很多关于孵化的discussion,现在引入了一些更改,使孵化变得更加直观。

如果使用facecolor参数而不是color参数,问题中的示例现在可以按预期再次运行。

import matplotlib.pyplot as plt

plt.plot([0,1],[0,1],ls="--",c="b")
plt.fill_between([0,1],[0,1], facecolor="none", hatch="X", edgecolor="b", linewidth=0.0)
plt.show()

enter image description here

matplotlib 2.0.0

保留原帖,导致此问题:
在matplotlib 2.0.0中,您可以使用plt.style.use('classic')来恢复旧样式。

##Classic!
import matplotlib.pyplot as plt
plt.style.use('classic')
plt.rcParams['hatch.color'] = 'b'

plt.plot([0,1],[0,1],ls="--",c="b")
plt.fill_between([0,1],[0,1], color="none", hatch="X", edgecolor="b", linewidth=0.0)

plt.show()

如果不设置旧样式,则不将颜色设置为none,而是将其设置为透明。

## New
import matplotlib.pyplot as plt
plt.rcParams['hatch.color'] = 'b'

plt.plot([0,1],[0,1],ls="--",c="b")
plt.fill_between([0,1],[0,1], hatch="X", linewidth=0.0, alpha=0.0)

plt.show()

这两种方法都依赖于通过plt.rcParams['hatch.color'] = 'b'设置阴影颜色。

不幸的是,目前还没有其他方法可以在matplotlib 2.0.0中设置填充颜色 matplotlib page that explains the changes

  

没有舱口颜色或线宽的API级别控制。

github上有一个issue on this topic,并且可以在即将推出的版本中添加API控件(实际上是使用版本2.0.1完成)

答案 1 :(得分:2)

发布了matplotlib 2.0.1 we now have much better control of the hatching

目前,我可以找到删除背景颜色(如提问)的唯一方法是在color = None, alpha = 0 args中设置fill_between。这可以按照要求工作,但不幸的是导致相当无用的传说。

感谢QuLogic指出我应该使用facecolor = 'none'这现在完美无缺。

from matplotlib import pyplot as plt
import numpy as np

def plt_hist(axis, data, hatch, label):
    counts, edges = np.histogram(data, bins=int(len(data)**.5))
    edges = np.repeat(edges, 2)
    hist = np.hstack((0, np.repeat(counts, 2), 0))

    outline, = ax.plot(edges,hist,linewidth=1.3)        
    axis.fill_between(edges,hist,0,
                edgecolor=outline.get_color(), hatch = hatch, label=label, 
                facecolor = 'none')  ## < removes facecolor
    axis.set_ylim(0, None, auto = True)

h1 = '//'
d1 = np.random.rand(130)
lab1 = 'Rand1'
h2 = '\\\\'
d2 = np.random.rand(200)
lab2 = 'Rand2'

fig, ax = plt.subplots(1)

plt_hist(ax,d1,h1,lab1)
plt_hist(ax,d2,h2,lab2)
ax.legend()

example plot