Python学习之Matplotlib (一)

Matplotlib




Matplotlib 是一个 Python 的 2D绘图库,能够生成出版质量级别的图形


一、简介

import numpy as np  
import matplotlib.pyplot as plt  
  
# 初始化x轴变量  
x1 = np.linspace(-2,2,1000) # 返回一个数组x1,数组元素从1递增到5,一共1000个元素  
x2 = np.arange(-2,2,0.001) # 返回一个数组x2,数组元素从1递增到5,步长为0.001  
  
# 设置y轴变量  
y1 = 1 + np.sin(np.pi*x1)  
y2 = 1 + np.cos(np.pi*x2)  
  
# 图1  
plt.subplot(1,2,1) # 作用同matlab中的subplot  
plt.plot(x1, y1, label='Sinusoidal function', color='red', linewidth=1.0, linestyle='--')   
plt.title('fig 1') # 标题  
plt.xlabel('x1') # 设置x轴变量名  
plt.ylabel('y1') # 设置y轴变量名  
  
# 图2  
plt.subplot(1,2,2)  
plt.plot(x2, y2, label='cosine function', color='green', linewidth=1.0, linestyle='-')  
plt.legend() # 设置图例  
plt.xlim((-3,3)) # 设置x轴取值范围  
plt.ylim((0,4)) # 设置y轴取值范围  
plt.title('fig 2')  
plt.xlabel('x2')  
plt.ylabel('y2')
plt.tight_layout() # 自动调整子图之间的距离


二、直方图


Barchart Demo        matplotlib.pyplot.bar


import numpy as np
import matplotlib.pyplot as plt

n_groups = 5 

precision1 = (0.82, 0.91, 0.87, 0.79, 0.93) # 期望值
std_p1 = (0.04, 0.03, 0.04, 0.09, 0.06) # 方差

precision2 = (0.85, 0.78, 0.94, 0.89, 0.85)
std_p2 = (0.07, 0.05, 0.09, 0.03, 0.03)

precision3 = (0.82, 0.88, 0.74, 0.81, 0.95)
std_p3 = (0.04, 0.07, 0.08, 0.05, 0.08)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.25 # 设置直方图宽度

opacity = 0.4
error_config = {'ecolor': '0.3'}

rects1 = ax.bar(index, precision1, bar_width,
                alpha=opacity, color='b',
                yerr=std_p1, error_kw=error_config,
                label='precision1')

rects2 = ax.bar(index + bar_width, precision2, bar_width,
                alpha=opacity, color='g',
                yerr=std_p2, error_kw=error_config,
                label='precision2')

rects3 = ax.bar(index + 2*bar_width, precision3, bar_width,
                alpha=opacity, color='r',
                yerr=std_p3, error_kw=error_config,
                label='precision3')

ax.set_xlabel('time(s)')
ax.set_ylabel('Precision')
ax.set_title('precision changed by time')
ax.set_xticks(index + bar_width)
ax.set_xticklabels(('1:00', '3:00', '5:00', '7:00', '9:00'))
ax.legend()

fig.tight_layout()
plt.show()


三、填充

Fill plot demo        matplotlib.pyplot.fill        


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) - 0.5

plt.fill(x,y,'g')
plt.show()









猜你喜欢

转载自blog.csdn.net/liang_gu/article/details/78756297
今日推荐