有没有办法增加matplotlib中的影线宽度?
例如,通过指定linewidth
,以下代码仅更改边缘的宽度。我想改变用于填充的线的线宽。
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(100)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(x, fill=False, hatch='/', linewidth=2)
plt.show()
答案 0 :(得分:13)
从matplotlib 2.0版开始,您可以directly change the linewidth parameter,如下所示:
import matplotlib as mpl
mpl.rcParams['hatch.linewidth'] = 0.1 # previous pdf hatch linewidth
mpl.rcParams['hatch.linewidth'] = 1.0 # previous svg hatch linewidth
这似乎是一个比上面人们更好的解决方法。您可以通过以下方式检查matplotlib版本:
import matplotlib as mpl
print(mpl.__version__) # should be 2.x.y
答案 1 :(得分:4)
如果您使用pdf并拥有sudo权限,则可以在backend_pdf.py中更改它。有一行
self.output(0.1, Op.setlinewidth)
通常它位于/usr/lib/pymodules/python2.7/matplotlib/backends/backend_pdf.py。
还有人写了一个黑客来从你的脚本执行此操作(仍然需要执行sudo权限)。解决方案来自:http://micol.tistory.com/358
import os
import re
import matplotlib
def setHatchThickness(value):
libpath = matplotlib.__path__[0]
backend_pdf = libpath + "/backends/backend_pdf.py"
with open(backend_pdf, "r") as r:
code = r.read()
code = re.sub(r'self\.output\((\d+\.\d+|\d+)\,\ Op\.setlinewidth\)',
"self.output(%s, Op.setlinewidth)" % str(value), code)
with open('/tmp/hatch.tmp', "w") as w:
w.write(code)
print backend_pdf
os.system('sudo mv /tmp/hatch.tmp %s' % backend_pdf)
setHatchThickness(1.0)
答案 2 :(得分:2)
有一个非常hacky的解决方案,但允许你在不改变matplotlib内部文件的情况下做你想做的事情:你可以像这样修补PdfFile的writeHatches:
CURRENT + " lineend"
然后你可以做
# make sure you have the correct imports,
# they may differ depending on the matplotlib version
import matplotlib.backends.backend_pdf
from matplotlib.externals import six
from matplotlib.backends.backend_pdf import Name, Op
from matplotlib.transforms import Affine2D
def setCustomHatchWidth(customWidth):
def _writeHatches(self):
COPY CODE FROM matplotlib.__path__[0] + "/backends/backend_pdf.py" HERE
change the line
self.output(0.1, Op.setlinewidth)
to
self.output(customWidth, Op.setlinewidth)
matplotlib.backends.backend_pdf.PdfFile.writeHatches = _writeHatches
之前保存你的数字为pdf。
答案 3 :(得分:0)