我有几个使用matplotlib创建的子图。绘制数据后,我需要返回并在for循环中的数据点之间绘制线条。我的数据文件很大,这需要python很长时间......
有没有办法加快速度?这是我的代码:
def generateHistogram(x, y, ax):
x = np.log10(x)
xerror = []
numData = len(x)
plt.rcParams['lines.solid_capstyle'] = 'butt'
for dataIndex in range(0, numData-1):
xerror.append(np.divide(np.subtract(x[dataIndex+1], x[dataIndex]), 2.0))
for errorIndex in range(0, len(x)):
if (errorIndex == 0):
ax.semilogx((np.power(10, (x[errorIndex]-xerror[errorIndex])), np.power(10, x[errorIndex])),
(y[errorIndex], y[errorIndex]), linewidth=2, color='k')
if (errorIndex == len(xerror)):
ax.semilogx((np.power(10, x[errorIndex]), np.power(10, (x[errorIndex]+xerror[errorIndex-1]))),
(y[errorIndex], y[errorIndex]), linewidth=2, color='k')
if (errorIndex < len(xerror)):
ax.semilogx((np.power(10, x[errorIndex]), np.power(10, (x[errorIndex]+xerror[errorIndex]))),
(y[errorIndex], y[errorIndex]), linewidth=2, color='k')
ax.semilogx((np.power(10, (x[errorIndex+1]-xerror[errorIndex])), np.power(10, x[errorIndex+1])),
(y[errorIndex+1], y[errorIndex+1]), linewidth=2, color='k')
verticleLineXPos = np.power(10, (x[errorIndex]+xerror[errorIndex]))
ax.semilogx((verticleLineXPos, verticleLineXPos), (y[errorIndex], y[errorIndex+1]),
linewidth=2, color='k')
return xerror;
这基本上在我需要的位置上绘制每个子图(其中x轴是半轴刻度)的线。您对提高性能有什么建议吗?
答案 0 :(得分:2)
我在这里找到了这个引用,它提供了一种聪明的方法来优化它:http://exnumerus.blogspot.com/2011/02/how-to-quickly-plot-multiple-line.html
它提供99%的性能提升。它对我很有用。
答案 1 :(得分:0)
当您需要将不同的kwargs传递到不同的行时
grover's Answer 非常适合您不需要将任何额外的kwargs
传递给个别行。
但是,如果你这样做(就像我一样)那么你就不能使用他的链接中列出的一次通话方法。
在检查了plot
花费时间的时间之后,特别是在使用循环绘制同一轴上的多条线时,结果显示浪费了很多时间自动缩放添加每个内部Line2D
对象后的视图。
为了解决这个问题,我们可以重复使用plot
函数(see here on the github repo)的内部结构,但只在我们完成时调用autoscale_view
函数一次。
这提供了~x2的加速,虽然不在任何地方附近
通过一次传递所有绘图参数所提供的速度,对于需要传递不同kwargs
的情况(例如特定的线条颜色)仍然有用。
以下示例代码。
import numpy as np
import matplotlib.pyplot as plt
Nlines = 1000
Npoints = 100
fig = plt.figure()
ax = fig.add_subplot(111)
xdata = (np.random.rand(Npoints) for N in range(Nlines))
ydata = (np.random.rand(Npoints) for N in range(Nlines))
colorvals = (np.random.rand() for N in range(Nlines))
for x, y, col in zip(xdata, ydata, colorvals):
ax.add_line(
plt.Line2D(
x,y,
color=plt.cm.jet(col)
)
)
ax.autoscale_view()