python画图

1、双y轴

x = np.arange(0., np.e, 0.01)
y1 = np.exp(-x)
y2 = np.log(x)
fig = plt.figure()

ax1 = fig.add_subplot(111)
ax1.plot(x, y1)
ax1.set_ylabel('Y values for exp(-x)')
ax1.set_title("Double Y axis")

ax2 = ax1.twinx()  # this is the important function
ax2.plot(x, y2, 'r')
ax2.set_xlim([0, np.e])
ax2.set_ylabel('Y values for ln(x)')
ax2.set_xlabel('Same X for both exp(-x) and ln(x)')
plt.show()

2、分段画图

def sgn(value):
    if value < 4:
        return 20
    else:
        return 15
plt.figure(figsize=(6,4))
x = np.linspace(0, 8, 100)
y = np.array([])
for v in x:
    y = np.append(y,np.linspace(sgn(v),sgn(v),1))
l=plt.plot(x,y,'b',label='type')
plt.legend()
plt.show()

3、绘制函数图形及数值拟合

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
#用指数形式来拟合
x = np.arange(1, 17, 1)
y = np.array([4.00, 6.40, 8.00, 8.80, 9.22, 9.50, 9.70, 9.86, 10.00, 10.20, 10.32, 10.42, 10.50, 10.55, 10.58, 10.60])
def func(x,a,b):
    return a*np.exp(b/x)
popt, pcov = curve_fit(func, x, y)
a=popt[0]#popt里面是拟合系数,读者可以自己help其用法
b=popt[1]
yvals=func(x,a,b)
plot1=plt.plot(x, y, '*',label='original values')
plot2=plt.plot(x, yvals, 'r',label='curve_fit values')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.legend(loc=4)#指定legend的位置,读者可以自己help它的用法
plt.title('curve_fit')
plt.show()
plt.savefig('p2.png')

4.1、添加标签

#使用自己下载的宋体库simsun.ttc,原始matplotlib不支持中文
myfont = matplotlib.font_manager.FontProperties(fname="simsun.ttc")
plt.rcParams['axes.unicode_minus'] = False

dates,y1 = np.loadtxt('全国发病数据_可用于分析.csv', delimiter=',', usecols=(0,1), unpack=True)
dates,y2 = np.loadtxt('全国发病数据_可用于分析.csv', delimiter=',', usecols=(0,2), unpack=True)

plt.gcf().set_facecolor(np.ones(3) * 240/255)#设置背景色
fig, ax1 = plt.subplots() # 使用subplots()创建窗口
ax2 = ax1.twinx() # 创建第二个坐标轴
ax1.plot(dates, y1,'o-', c='orangered',label='y1', linewidth = 1) #绘制折线图像1,圆形点,标签,线宽
ax2.plot(dates, y2, 'o-', c='blue',label='y2', linewidth = 1) #同上

ax1.set_xlabel('时间', fontproperties=myfont,size=18) #与原始matplotlib设置参数略有不同,使用自己下载的中文宋体,参数位置不可改变
ax1.set_ylabel('第1列数据', fontproperties=myfont,size=18)
ax2.set_ylabel('第2列数据', fontproperties=myfont,size=18)
plt.gcf().autofmt_xdate()#自动适应刻度线密度,包括x轴,y轴

plt.legend()#显示折线的意义
plt.show()

4.2、解决标签不显示的问题

fig, ax1 = plt.subplots() 
ax1.plot(dates, y1,'o-', c='orangered',label='cancer viliage num', linewidth = 1) 
plt.legend(loc=2)
ax2 = ax1.twinx() 
ax2.plot(dates, y2, 'o-', c='blue',label='waster water', linewidth = 1)
plt.legend(loc=1)

  说明:在plt.legend()中添加了参数loc,而对应值1,2,3,4分别对应图像的右上角,左上角,左下角,右下角

5、同一坐标画图

plt.figure(1)
x_axis = pd.to_datetime(data2['sample_time'],dayfirst=True).tolist() plt.plot(x_axis, data2['value'],"b-",label = '瞬时流量',linewidth = 2) plt.plot(x_axis,y3,"g-",label="均值",linewidth=2) plt.legend() plt.show()

  

原文地址:https://www.cnblogs.com/xxupup/p/12015742.html