Matplotlib平滑折线图的xticks与marker函数使用问题
平滑折线图的两个优化问题及解决方案
我通过以下代码实现了更平滑的折线图:
import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import make_interp_spline # 创建随机数据 years = list(range(1998, 2021, 1)) print(len(years)) # 23 random_values = [86, 78, 63, 56, 100, 72, 59, 71, 84, 89, 62, 57, 56, 73, 92, 52, 77, 60, 84, 64, 86, 80, 59] idx = range(len(years)) xnew = np.linspace(min(idx), max(idx), 300) # 插值处理 spl = make_interp_spline(idx, random_values, k=3) smooth = spl(xnew) # 绘图并替换刻度 plt.plot(xnew, smooth, color = 'black', marker = '.') plt.xticks(idx, years) plt.show()
生成的图表如下:
基于该图表,存在两个技术问题:
- 如何限制x轴刻度仅显示2000、2005、2010、2015和2020年?当前使用
plt.xticks()传入两个参数,配置难度较高。 - 如何将标记点数量限制为与年份数量一致(最终显示23个标记点),且匹配对应年份的位置?
问题1:自定义x轴显示刻度
无需传入所有年份的索引和值,直接指定目标年份及其对应的位置即可:
# 指定要显示的年份 target_years = [2000, 2005, 2010, 2015, 2020] # 获取这些年份在原始列表中的索引位置 target_indices = [years.index(y) for y in target_years] # 设置x轴刻度 plt.xticks(target_indices, target_years)
这样x轴就只会展示你需要的年份,避免了处理全部23个年份的繁琐操作。
问题2:匹配原始年份的标记点
当前代码在插值后的300个点上绘制标记,导致数量过多。正确做法是分离平滑曲线和标记点的绘制:先画不带标记的平滑曲线,再单独绘制原始数据的标记点,确保标记精准对应每个年份的位置:
# 绘制平滑曲线(无标记) plt.plot(xnew, smooth, color='black') # 绘制原始数据的标记点(仅显示标记,无连线) plt.plot(idx, random_values, color='black', marker='.', linestyle='None') # 应用问题1的刻度设置 target_years = [2000, 2005, 2010, 2015, 2020] target_indices = [years.index(y) for y in target_years] plt.xticks(target_indices, target_years) plt.show()
修改后,平滑曲线保持完整,同时每个原始年份位置都会显示一个标记点,总数正好为23个,x轴刻度也仅展示指定年份。
内容的提问来源于stack exchange,提问作者Foeke Boersma
相关产品推荐
相关产品推荐

