matplotlib/pyplot绘制分组散点图时代码缩进报错问题
问题原因与修复方案
缩进错误
你仅对x, y = data做了缩进,ax.scatter()语句属于for循环的执行逻辑,同样需要缩进在循环内部,否则循环执行时只会重复赋值x、y,不会逐组绘制散点,循环结束后仅会尝试绘制最后一组数据,还可能触发变量相关报错。
废弃参数错误
你用到的axisbg是matplotlib早期版本的废弃参数,目前版本需要替换为facecolor才能正常设置子图背景色,这是触发AttributeError的核心原因。
完整可运行修正代码
import numpy as np import matplotlib.pyplot as plt # Create data N = 60 g1 = (0.6 + 0.6 * np.random.rand(N), np.random.rand(N)) g2 = (0.4+0.3 * np.random.rand(N), 0.5*np.random.rand(N)) g3 = (0.3*np.random.rand(N),0.3*np.random.rand(N)) data = (g1, g2, g3) colors = ("red", "green", "blue") groups = ("coffee", "tea", "water") # Create plot fig = plt.figure() # 把废弃的axisbg替换为facecolor ax = fig.add_subplot(1, 1, 1, facecolor="1.0") for data, color, group in zip(data, colors, groups): x, y = data # scatter语句缩进至for循环内部 ax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group) plt.title('Matplot scatter plot') plt.legend(loc=2) plt.show()
内容的提问来源于stack exchange,提问作者Jessie
相关产品推荐
相关产品推荐

