Matplotlib添加柱状图数值时出现Image size过大错误的解决方法
问题描述
我有如下数据:
基于该数据创建可视化图表的代码如下:
# create the visualization of the data fig = plt.figure(figsize=(10, 5)) #to set the figure size fig.suptitle('Number of Transaction per day', fontsize=20) # to set the chart title and its font size plt.xlabel('Day', fontsize=20) # to set the axis title and its font size plt.ylabel('number of transaction', fontsize=20) # to set the axis title and its font size x = eda_2['Day'] # load the data to be used for that axis y = eda_2['number of transaction'] # load the data to be used for that axis plt.bar(x, y, color = 'green') # to plot and select the line colour plt.grid(color='darkgray', linestyle=':', linewidth=0.5) plt.show() # to show the chart
生成的图表如下:
我希望为每个柱状条显示对应数值,添加了以下代码:
for index, value in enumerate(y): plt.text(value, index, str(value))
执行后出现错误:Image size of 537447x362 pixels is too large. It must be less than 2^16 in each direction. 请问该如何解决?
解决方法
错误根源是plt.text()的参数顺序颠倒了:你把柱子的高度(value)当成了x坐标,把索引(index)当成了y坐标,导致文本被渲染到了x轴极端大值的位置,触发了图片尺寸超限的报错。
柱状图中,plt.text()的正确用法是传入**(柱子的x轴位置, 柱子的高度, 要显示的数值)**,还可以添加对齐参数让文本更美观。修正后的完整代码如下:
# 创建可视化图表 fig = plt.figure(figsize=(10, 5)) fig.suptitle('Number of Transaction per day', fontsize=20) plt.xlabel('Day', fontsize=20) plt.ylabel('number of transaction', fontsize=20) x = eda_2['Day'] y = eda_2['number of transaction'] plt.bar(x, y, color='green') plt.grid(color='darkgray', linestyle=':', linewidth=0.5) # 修正后的数值标注代码 for idx, val in enumerate(y): # x坐标用对应日期,y坐标在柱子高度基础上稍作偏移,避免重合 plt.text(x[idx], val + 15, str(val), ha='center', fontsize=12) plt.show()
补充说明:
ha='center'让文本在柱子顶部居中,提升可读性- 偏移量
+15可以根据你的实际数据范围调整,确保文本和柱子不重叠
内容的提问来源于stack exchange,提问作者lilpearce
相关产品推荐
相关产品推荐

