如何将字典列表按升序提取为整数列表用于Matplotlib绘图?
解决方案
1. 数据预处理
你的字典列表每个元素都是单键值对,先提取所有年份和对应数值并转换为整数,再按年份升序排序:
# 原始数据 data = [ {'1994': 5}, {'1972': 1}, {'1974': 1}, {'2008': 2}, {'1957': 3}, {'1993': 1}, {'2003': 2}, {'1966': 1}, {'1999': 4}, {'2001': 3}, {'1980': 2}, {'2010': 2}, {'2002': 3}, {'1975': 1}, {'1990': 1}, {'1954': 2}, {'1977': 1}, {'1995': 4}, {'1991': 2}, {'1946': 1}, {'1997': 2}, {'1998': 2}, {'2014': 2}, {'1960': 1}, {'1968': 2}, {'1931': 2}, {'1942': 1}, {'2011': 1}, {'1936': 1}, {'2006': 3}, {'1981': 2}, {'1985': 1}, {'2000': 4}, {'1979': 2}, {'1940': 1}, {'1988': 2}, {'1950': 1}, {'1964': 1}, {'2017': 1}, {'2012': 2}, {'1986': 1}, {'1984': 2}, {'1941': 1}, {'1959': 1}, {'1958': 1}, {'1992': 1}, {'1983': 1}, {'2016': 2}, {'2007': 1}, {'1971': 1}, {'1962': 2}, {'2004': 1}, {'1944': 1}, {'1976': 1}, {'1952': 1}, {'2009': 2}, {'1987': 1}, {'1973': 1}, {'1948': 1}, {'1921': 1} ] # 提取键值对并转换为整数元组 year_value_pairs = [] for item in data: year_str, value = next(iter(item.items())) year_value_pairs.append( (int(year_str), value) ) # 按年份升序排序 year_value_pairs.sort(key=lambda x: x[0]) # 拆分为两个独立整数列表 years = [pair[0] for pair in year_value_pairs] values = [pair[1] for pair in year_value_pairs]
2. 使用Matplotlib绘图
得到排序后的列表后,可根据需求绘制柱状图或折线图:
柱状图示例
import matplotlib.pyplot as plt # 设置绘图风格 plt.style.use('seaborn-v0_8') # 绘制柱状图 plt.bar(years, values, color='#1f77b4') # 添加图表元素 plt.title('Year vs Value', fontsize=14) plt.xlabel('Year', fontsize=12) plt.ylabel('Value', fontsize=12) # 旋转X轴标签避免重叠 plt.xticks(rotation=45) # 调整布局防止标签截断 plt.tight_layout() # 显示图表 plt.show()
折线图示例
只需把plt.bar替换为plt.plot即可:
plt.plot(years, values, marker='o', linestyle='-', color='#ff7f0e')
补充说明
- 用
next(iter(item.items()))可快速取出单键值对字典的键和值,比遍历更高效 - 排序时指定
key=lambda x: x[0]确保按年份升序排列 - 旋转X轴标签和
tight_layout()是为了提升图表可读性
内容的提问来源于stack exchange,提问作者TheHotch
相关产品推荐
相关产品推荐

