这个错误是由于在绘制折线图时,x和y的维度不匹配引起的。根据需求,x的长度是10,而y1和y2的长度分别是900和100。要解决这个问题,可以修改代码如下:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 90, 10)
y1 = [0, 180, 160, 140, 150, 130, 140, 140, 130, 130,
      140, 140, 150, 130, 140, 130, 130, 140, 140, 140,
      130, 130,150, 130, 130, 150, 130, 140, 140, 140,
      130, 140, 140, 150, 130, 150, 140, 130, 130, 130,
      140, 130, 140, 150,140, 130, 130, 130, 150, 130,
      130, 150, 130, 130, 140, 140, 130, 140, 140, 140,
      130, 130, 130, 140, 130, 130,160, 130, 130, 130,
      140, 130, 140, 130, 160, 130, 130, 130, 140, 130,
      130, 140, 140, 130, 130, 140, 130, 130,140, 140]
y2 = [87600, 87420, 87260, 87120, 86970, 86840, 86700, 86560, 86430, 86300,
      86160, 86020, 85870, 85740, 85600,85470, 85340, 85200, 85060, 84920,
      84790, 84660, 84510, 84380, 84250, 84100, 83970, 83830, 83690, 83550,
      83420, 83280, 83140, 82990, 82860, 82710, 82570, 82440, 82310, 82180,
      82040, 81910, 81770, 81620, 81480,81350, 81220, 81090, 80940, 80810, 
      80680, 80530, 80400, 80270, 80130, 79990, 79860, 79720, 79580, 79440,
      79310, 79180, 79050, 78910, 78780, 78650, 78490, 78360, 78230, 78100, 
      77960, 77830, 77690, 77560, 77400,77270, 77140, 77010, 76870, 76740,
      76610, 76470, 76330, 76200]

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()

在修改后的代码中,我将绘制折线图的代码中的x和y的长度都修改为了10,这样就解决了维度不匹配的问题。

Python绘图报错:x和y维度不匹配的解决方法

原文地址: https://www.cveoy.top/t/topic/f6Lu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录