python matplotlib画图总结——第二篇

1、两条曲线拟合求其交点

import scipy.interpolate, scipy.optimize
import numpy as np
x = np.array([])
y1 = np.array([])
y2 = np.array([])

interp1 = scipy.interpolate.InterpolatedUnivariateSpline(x, y1)
interp2 = scipy.interpolate.InterpolatedUnivariateSpline(x, y2)

def difference(x):
    return np.abs(interp1(x) - interp2(x))

cross_x = scipy.optimize.fsolve(difference, x0=x_0)  # 为交点的横坐标集合,x_0为初值
cross_y = interp1(cross_x)  # 为交点的纵坐标集合


2、将坐标轴移到任意位置

import matplotlib.pyplot as plt

ax = plt.gca()
plt.xlim([-10, 10])
plt.ylim([-10, 10])
ax.spines['top'].set_visible(False)  # 去掉上面的框线
ax.spines['right'].set_visible(False)  # 去掉右边的框线
ax.spines['bottom'].set_position(('data', 5))
ax.spines['left'].set_position(('axes', 0.5))
# 对'data',就是移到数据点处
# 对'axes',把整个横轴长度看成1,0.5就是y轴位置在横轴长度的一半处,所以只能0-1之间
plt.xlabel('x', labelpad=-30.0, fontsize=10, loc='right')
# x坐标标签显示在右边,labelpad是标签距离轴的距离
plt.ylabel('y', labelpad=-50.0, fontsize=10, loc='top', rotation=0)  
# y坐标标签显示在上边,并且旋转度数为0(默认为90)
plt.show()

结果如下图所示。

python matplotlib画图总结——第二篇_第1张图片

 3、图例

fig = plt.figure()
fig.legend(loc='center', ncol=1) 

fig.legend是给整图加标签,如果是plt.legend则是给专门的图线加标签。
ncol表示把图例分为ncol列。

4、跑题了的数组

把n中的index所表示下标的元素变成0:

t = np.array([1, 2, 3, 4, 5])
n = np.array([1, 2, 3, 4, 5])
index = np.argwhere(t >= 3)  # 找到t中大于等于3的下标(2,3,4)
n[index] = 0  # 即n[2]=0,n[3]=0,n[4]=0 

你可能感兴趣的:(matplotlib画图,python,matplotlib)