求助:无法使用Matplotlib生成单图三线折线图
问题与解决方案
问题说明
需要在同一Matplotlib图表中展示三条基于FIFO页面置换算法的折线图,FIFO函数逻辑正确、返回值符合预期,但当前代码无法实现三线同图的清晰展示效果。
问题分析
原代码中三条折线的x轴取值范围不同(分别为1-3、1-4、1-5),虽Matplotlib会自动适配坐标轴,但易造成折线重叠或视觉混淆;同时三条折线样式区分度不足,进一步影响直观展示。
修改后的代码
import matplotlib.pyplot as plt import numpy as np def fifo_page_replacement(num_frames, reference_string): frame_list = [] # 存储当前分配的页帧 fault_count = 0 # 页错误计数器 for page in reference_string: if page not in frame_list: fault_count += 1 if len(frame_list) == num_frames: # 移除最早进入的页 frame_list.pop(0) # 添加新页到页帧 frame_list.append(page) return fault_count # 示例数据 reference_string = [1,2,3,4,2,1,5,6,2,1,2,3,7,6,3,2,1,2,3,6] # 统一x轴范围为1到5,覆盖三条折线的所有取值 x_common = np.arange(1, 6) # 计算三组页错误数,用None补全数据长度以匹配统一x轴 page_faults_1 = [fifo_page_replacement(frame, reference_string) for frame in x_common[:3]] + [None, None] page_faults_2 = [fifo_page_replacement(frame, reference_string) for frame in x_common[:4]] + [None] page_faults_3 = [fifo_page_replacement(frame, reference_string) for frame in x_common] # 绘图优化 plt.figure(figsize=(10,6)) plt.plot(x_common, page_faults_1, label="折线1(1-3帧)", marker="o", color="blue", linestyle="-") plt.plot(x_common, page_faults_2, label="折线2(1-4帧)", marker="s", color="orange", linestyle="--") plt.plot(x_common, page_faults_3, label="折线3(1-5帧)", marker="^", color="green", linestyle=":") plt.xlabel("页帧数量") plt.ylabel("页错误次数") plt.title("FIFO页面置换算法页错误对比") plt.grid(True, alpha=0.3) plt.legend() plt.xticks(x_common) plt.show()
关键修改点
- 统一x轴范围,确保三条折线在同一坐标系下对齐显示
- 为每条折线设置差异化的颜色、标记和线型,提升视觉区分度
- 用
None补全较短折线的数据,使其长度与统一x轴匹配 - 调整图表尺寸、网格透明度和x轴刻度,优化整体可读性
内容的提问来源于stack exchange,提问作者Sohaib Malik
相关产品推荐
相关产品推荐

