Matplotlib分组条形图首条不显示及Y轴调整技术咨询
解决Matplotlib分组条形图第一个条形不显示的问题
问题描述
使用Matplotlib绘制分组条形图时,第一个条形完全未显示。推测是Y轴刻度设置问题,尝试多种方法未解决。当前Y轴从最小数值开始,需在不破坏原有刻度比例的前提下修复。
原代码
from matplotlib import pyplot as plt import numpy as np x = np.arange(4) # the label locations width = 0.2 # the width of the bars plt.bar(x-0.2, one_digit_10_pre_run, width, color='cyan') plt.bar(x, two_digit_10_pre_run, width, color='orange') plt.bar(x+0.2, three_digit_10_pre_run,width,color='green') plt.xticks(x, ['10', '20', '30', "100"]) plt.xlabel("Amount of Input Values") plt.ylabel("Execution Times [Seconds]") plt.legend(["0 Digits extra", "1 Digit Extra", "2 Digit Extra"]) plt.show()
原始数据
['0.021636664867401074', '0.023439047336578315', '0.023759815692901566', 027013454437255814] [' 0.021725461034491467', ' 0.020219009701568258', ' 0.021416027545928907', ' 0.024219112396240184'] [' 0.02276699304580684', ' 0.021797661781310988', ' 0.025862150192260697', ' 0.026579418182373003']
问题分析与修复步骤
1. 数据类型修正
原始数据存在两个问题:
- 第一个列表最后一个元素
027013454437255814是非法八进制整数(以0开头),与其他字符串格式的浮点数不统一; - 部分数据带有多余空格。
先将所有数据转换为浮点数:
one_digit_10_pre_run = [float(num.strip()) for num in ['0.021636664867401074', '0.023439047336578315', '0.023759815692901566', '0.027013454437255814']] two_digit_10_pre_run = [float(num.strip()) for num in [' 0.021725461034491467', ' 0.020219009701568258', ' 0.021416027545928907', ' 0.024219112396240184']] three_digit_10_pre_run = [float(num.strip()) for num in [' 0.02276699304580684', ' 0.021797661781310988', ' 0.025862150192260697', ' 0.026579418182373003']]
2. Y轴刻度调整
Y轴从最小值开始时,条形底部会被坐标轴截断。通过设置略低于最小值的Y轴下限,既能显示完整条形,又不破坏原有刻度比例:
# 获取所有数据的最小值 all_data = one_digit_10_pre_run + two_digit_10_pre_run + three_digit_10_pre_run min_val = min(all_data) # 设置Y轴下限为最小值的95% plt.ylim(bottom=min_val * 0.95)
3. 完整修正代码
from matplotlib import pyplot as plt import numpy as np # 修正后的数据 one_digit_10_pre_run = [float(num.strip()) for num in ['0.021636664867401074', '0.023439047336578315', '0.023759815692901566', '0.027013454437255814']] two_digit_10_pre_run = [float(num.strip()) for num in [' 0.021725461034491467', ' 0.020219009701568258', ' 0.021416027545928907', ' 0.024219112396240184']] three_digit_10_pre_run = [float(num.strip()) for num in [' 0.02276699304580684', ' 0.021797661781310988', ' 0.025862150192260697', ' 0.026579418182373003']] x = np.arange(4) width = 0.2 plt.bar(x-0.2, one_digit_10_pre_run, width, color='cyan') plt.bar(x, two_digit_10_pre_run, width, color='orange') plt.bar(x+0.2, three_digit_10_pre_run, width, color='green') plt.xticks(x, ['10', '20', '30', "100"]) plt.xlabel("输入值数量") plt.ylabel("执行时间 [秒]") plt.legend(["0位额外数字", "1位额外数字", "2位额外数字"]) # 调整Y轴下限 all_data = one_digit_10_pre_run + two_digit_10_pre_run + three_digit_10_pre_run min_val = min(all_data) plt.ylim(bottom=min_val * 0.95) plt.show()
内容的提问来源于stack exchange,提问作者tapir36
相关产品推荐
相关产品推荐

