Python使用Matplotlib与Scipy绘制平滑坐标曲线图
本文介绍如何利用Python的Matplotlib和Scipy库绘制光滑的坐标曲线图。通过导入必要的第三方库,结合interpolate模块进行插值处理,实现从离散点到平滑曲线的转换。文章提供了完整的代码示例,包括坐标轴美化、范围设置及图例添加等进阶技巧,帮助开发者提升数据可视化的效果。
Python绘制平滑曲线图基础
在进行数据处理时,经常需要绘制坐标图表。本文将演示如何使用第三方库matplotlib配合scipy来生成光滑的曲线图。
执行该操作前,需确保已安装matplotlib、scipy以及numpy这三个必要的库。
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axisartist.axislines import Subplot
from scipy import interpolate
def sommth_plot(x_arr, y_arr):
fig = plt.figure() # 创建一个figure
ax = Subplot(fig, 111) # 利用Subplot将figure加入ax
fig.add_axes(ax)
ax.axis['bottom'].set_axisline_style("->", size=1.5) # x轴加上箭头
ax.axis['left'].set_axisline_style("->", size=1.5) # y轴加上上箭头
ax.axis['top'].set_visible(False) # 去除上方坐标轴
ax.axis['right'].set_visible(False) # 去除右边坐标轴
xmin = min(x_arr)
xmax = max(x_arr)
xnew = np.arange(xmin, xmax, 0.0005) # 在最大最小值间以间隔为0.0005插入点
func = interpolate.interp1d(x_arr, y_arr)
ynew = func(xnew) # 得到插入x对应的y值
plt.plot(xnew, ynew, '-') # 绘制图像
plt.show() # show图像
if __name__ == '__main__':
x = eval(input('输入x:'))
y = eval(input('输入y:'))
smooth_plot(x, y)
图像美化与进阶设置
若需进一步优化图像展示效果,可参考以下代码进行设置。
# 设置图像标题
plt.title('title')
# 设置x范围,y同理
plt.xlim(1, 4)
# 给x,y轴添加说明
plt.xlabel('x')
plt.ylabel('y')
# 设置线条的颜色,宽度,线条样式,标志以及曲线的标签
plt.plot(x, y, color='blue', linewidth=1.0, linestyle='--', marker='o', label='')
# 如果传递了label参量,则使用下面函数使标签显示,loc选择位置,frameon=True标签会在一个框内
plt.legend(loc='upper left', frameon=True)
以上内容为本文的全部分享,旨在为读者的学习提供辅助,同时也欢迎读者继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









