升级timeit_plot到Python3时matplotlib报Invalid RGBA错误求解
问题原因
报错核心是传递给matplotlib的RGBA颜色参数格式非法,根源来自你代码中折线图绘制分支的错误写法:
- 你在
style不为scatter/bubble的分支里,错误使用c=list(zip(c))给颜色参数赋值,直接把颜色迭代器做了zip处理,导致每个RGBA数组被额外套了一层tuple结构,和报错信息里出现的(array([0.5, 0. , 1. , 1. ]),)格式完全对应。 - 颜色迭代器的正确用法是每次循环调用
next(c)取一个颜色值,和散点图、气泡图分支的写法保持一致即可。
修复方案
直接修改折线图分支的传参即可解决问题:
将原有代码中:
ax.plot(v[series], v[-1], c=list(zip(c)), lw=2)
替换为:
ax.plot(v[series], v[-1], c=next(c), lw=2)
如果希望进一步规避迭代器使用的潜在问题,也可以将颜色生成逻辑调整为索引取值的形式,修改后完整函数如下:
def timeit_plot2D(data, xlabel='xlabel', title='title', **kwargs): """Plots the results from a defaultdict returned by timeit_compare. Each function will be plotted as a different series. timeit_compare may test many conditions, and the order of the conditions in the results data can be understood from the string substitutions noted in the keys of the defaultdict. By default series=0 means that the first series is plotted, but this can be changed to plot any of the testing conditions available. """ series = kwargs.get('series', 0) style = kwargs.get('style', 'line') size = kwargs.get('size', 500) ylabel = kwargs.get('ylabel', 'time') cmap = kwargs.get('cmap', 'rainbow') lloc = kwargs.get('lloc', 2) dataT = {} # 调整颜色生成逻辑为列表索引取值,更稳定 color_list = plt.get_cmap(cmap)(np.linspace(0, 1, len(data))) color_idx = 0 # transpose the data from [x, y, z]... into ([x...], [y...], [z...]) for k, v in data.items(): dataT[k] = list(zip(*v)) fig, ax = plt.subplots() for k, v in dataT.items(): current_color = color_list[color_idx] if style == 'scatter': ax.scatter(v[series], v[-1], s=size, c=current_color, alpha=.75) elif style == 'bubble': x, y, z = v[series[0]], v[series[1]], v[-1] ax.scatter(x, y, s=[size*i for i in z], c=current_color, alpha=.5) else: ax.plot(v[series], v[-1], c=current_color, lw=2) color_idx += 1 # TODO: BUG: no way to set other parameters manually (README fig2) ax.legend([substitute_titles(k,series) for k in dataT.keys()], loc=lloc) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_title(title) ax.grid(True) return fig
内容的提问来源于stack exchange,提问作者Major Redux
相关产品推荐
相关产品推荐

