Python Matplotlib 绘图错误:x 和 y 维度不匹配的解决方法
根据报错信息,可以看出问题出在第 79 行的 plt.plot() 函数中,导致报错的原因是 x 和 y 的维度不一致。x 的维度是 (9,),而 y 的维度是 (90,)。
解决这个问题的方法是将 y1 和 y2 的长度修改为与 x 相同的长度。可以通过切片操作来实现,将 y1 和 y2 的长度从 90 修改为 9。
修改后的代码如下:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.arange(0, 90, 10)
y1 = [0, 180, 160, 140, 150, 130, 140, 140, 130]
y2 = [87600, 87420, 87260, 87120, 86970, 86840, 86700, 86560, 86430]
plt.rcParams['font.sans-serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False
fig = plt.figure(figsize=(8, 6))
plt.xlim(0, 100)
plt.ylim(0, 90000)
plt.xticks(np.arange(0, 100, 10), ['0', '10', '20', '30', '40', '50', '60', '70', '80', '90'])
plt.yticks(np.arange(0, 100000, 10000), ['0', '1万', '2万', '3万', '4万', '5万', '6万', '7万', '8万', '9万'])
plt.xlabel('Variation', labelpad=10, fontsize='xx-large', color='#70AD47', fontweight='bold')
plt.ylabel('Capacity', labelpad=10, fontsize='xx-large', color='#70AD47', fontweight='bold')
plt.grid(b=True, linestyle='dashed', linewidth=1)
plt.title(label='SKU1 Variation与Capacity变化关系', loc='center')
for a, b in zip(x, y1):
plt.text(a, b, str(b), ha='center', va='bottom', fontsize=11)
for a, b in zip(x, y2):
plt.text(a, b, str(b), ha='center', va='bottom', fontsize=11)
plt.plot(x, y1, color='k', linestyle='solid', linewidth=1,
marker='o', markersize=3, label='折线图')
width = 3
plt.bar(x - width / 2, y2, width=width, color='k', label='柱形图')
plt.legend(loc='upper left')
plt.legend(ncol=2)
plt.annotate('服务器宕机了', xy=(60, 1), xytext=(70, 1), arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.savefig('sku1.png')
plt.show()
这样就能够运行成功并生成图像。
原文地址: https://www.cveoy.top/t/topic/f5sI 著作权归作者所有。请勿转载和采集!