为何我用Matplotlib绘制的折线与示例效果不符?
问题分析与解决方案
你的图表和预期效果的差异主要来自三个方面:轴刻度设置、线的样式/粗细与数据的对应关系。
1. 轴刻度差异
你当前代码里设置了包含中间值的刻度:
plt.xticks([10,15,20,25,30]) plt.yticks([10,15,20,25,30,35,40])
而预期图表的x/y轴只显示整数倍10的刻度,需要修改为:
plt.xticks([10,20,30]) plt.yticks([10,20,30,40])
2. 线的样式、粗细与数据对应错误
预期图表中:
- 蓝色粗虚线对应
y2数据(走势:从(10,40)降到(20,10)再升到(30,30)),标注为line1-dotted(这里是练习的标注小失误,实际样式为虚线) - 红色细点线对应
y1数据(走势:从(10,20)升到(20,40)再降到(30,10)),标注为line2-dashed
你当前的代码把数据、样式、粗细的对应关系搞反了,需要调整两条线的绘制代码:
# 蓝色粗虚线,对应y2数据 plt.plot(x2,y2,'b',label='line1-dotted',linewidth=5,linestyle='dashed') # 红色细点线,对应y1数据 plt.plot(x1,y1,'r',label='line2-dashed',linewidth=3,linestyle='dotted')
修正后的完整代码
import matplotlib.pyplot as plt # Variables x1 = [10,20,30] y1 = [20,40,10] x2 = [10,20,30] y2 = [40,10,30] # Plots(修正后) plt.plot(x2,y2,'b',label='line1-dotted',linewidth=5,linestyle='dashed') plt.plot(x1,y1,'r',label='line2-dashed',linewidth=3,linestyle='dotted') # Settings(修正轴刻度) plt.title('Plot with two or more lines with different styles') plt.xlabel('x - axis') plt.ylabel('y - axis') plt.xticks([10,20,30]) plt.yticks([10,20,30,40]) # Show Legends plt.legend(loc='upper right') # Show Plots plt.show()
运行修正后的代码,就能得到和预期一致的图表。
内容的提问来源于stack exchange,提问作者nutthawart
相关产品推荐
相关产品推荐

