Matplotlib绘制2012美国大选得票柱状图y轴数值异常求助
问题原因与解决方案
核心原因
你的图表y轴数值看起来远小于实际,大概率是Matplotlib对大数值默认启用了科学计数法,但仅显示了系数部分(比如把785万+的票数显示为7.85,省略了×10⁶的指数标注),并非实际数据被修改。
解决步骤
确认数据类型正确性
先确保votesOne和votesTwo中的元素是整数/浮点数,而非字符串(如果是字符串,Matplotlib会错误解析数据):# 若数据是字符串格式,执行转换 votesOne = list(map(int, votesOne)) votesTwo = list(map(int, votesTwo))关闭科学计数法,显示完整数值
用以下代码强制y轴显示完整的票数(带千位分隔符更易读):from matplotlib.ticker import FuncFormatter # 自定义格式化函数,添加千位分隔符 def format_vote_count(x, pos): return f"{int(x):,}" # 应用到y轴 plt.gca().yaxis.set_major_formatter(FuncFormatter(format_vote_count)) # 关闭科学计数法 plt.ticklabel_format(style='plain', axis='y')优化x轴标签显示(可选)
由于美国州名数量多,默认x轴标签会重叠,建议旋转标签并调整位置:# 让标签居中在两个柱状图中间,并旋转90度 plt.xticks(x + width/2, states, rotation=90, ha='center')
完整修正后代码示例
import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter states = ["Alabama", "Alaska", ...] # 你的州列表 votesOne = [795696, 122640, ...] # 奥巴马得票数据 votesTwo = [...] # 另一位候选人得票数据 mostVoted = ["Obama", ...] secondVoted = ["Romney", ...] x = np.arange(len(states)) y1 = votesOne y2 = votesTwo width = 0.2 plt.bar(x + 0.2, y1, width, color='cyan') plt.bar(x, y2, width, color='orange') # 优化x轴标签 plt.xticks(x + width/2, states, rotation=90, ha='center') plt.xlabel("States") plt.ylabel("Votes") plt.legend([mostVoted[0], secondVoted[0]]) # 格式化y轴显示完整票数 def format_vote_count(x, pos): return f"{int(x):,}" plt.gca().yaxis.set_major_formatter(FuncFormatter(format_vote_count)) plt.ticklabel_format(style='plain', axis='y') plt.tight_layout() # 自动调整布局,避免标签被截断 plt.show()
内容的提问来源于stack exchange,提问作者elassava
相关产品推荐
相关产品推荐

