python中matplotlib 的简单使用

1、简单折线图的画图,轴标签、图的颜色,风格,等等参数,本文只介绍最常用的几个参数:

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 x = np.linspace(-3,3,50)
 5 y1 = 2 * x + 1
 6 y2 = x ** 2
 7 
 8 plt.figure()  # figure 下面的图形都出现再这个figure中
 9 plt.plot(x,y2,label = 'up')   #label 为该图像的图例
10 plt.plot(x,y1,color = 'red',linewidth = 1.0,linestyle = '--',label = 'down')
11 plt.xlim((-1,2))  # 对x轴的范围限制
12 plt.ylim((-2,3))
13 plt.xlabel('I am X')  # x轴的标签
14 plt.ylabel('I am Y')
15 
16 # 边框删除
17 ax = plt.gca()  # gca: get current axis
18 ax.spines['right'].set_color('none')  # 获取当前位置的边框,进行设置
19 ax.spines['top'].set_color('none')
20 
21 # 坐标轴(边框)移动
22 ax.xaxis.set_ticks_position('bottom')
23 ax.yaxis.set_ticks_position('left')
24 ax.spines['bottom'].set_position(('data',0)) # 底部移动到 0
25 ax.spines['left'].set_position(('data',0)) # 左边移动到 0
26 
27 
28 # 图例
29 plt.legend()  # 打印出画图时加入的 label 参数
30 
31 #注释
32 x0 = 1
33 y0 = 2 * x0 +1
34 plt.scatter(x0,y0,s = 50,color = 'b')   # 找到要进行注释的一个坐标点
35 # plt.plot([x0,x0],[y0,0],'k--',linewidth = 2.5)  # 画一条竖直线
36 
37 # plt.annotate(r'$y=2x+1$',xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points')
38 
39 plt.text(-1,2,r'$This\ is\ \mu\ \sigma_i\ \alpha_t$',
40          fontdict={'size':16,'color':'r'}) # 数学符号前面加\转义符,显示数学符号
41 
42 plt.show()

 2、散点图

import matplotlib.pyplot as plt
import numpy as np

n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
# 散点图
T = np.arctan2(Y,X) # 颜色

plt.scatter(X,Y,s=75,c=T,alpha=0.5) # alpha 表示透明度
plt.xlim((-1.5,1.5))
plt.ylim((-1.5,1.5))

plt.show()

3、柱状图

# 柱状图
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5,1.0,n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5,1.0,n)

plt.bar(X,+Y1,facecolor='b',edgecolor = 'red')
plt.bar(X,-Y2)

for x,y in zip(X,Y1): # 在柱状图上加上高度值
    plt.text(x,y+0.05,'%.2f'%y,ha = 'center',va='bottom')#横向,纵向对齐方式

plt.show()

 4、等高线

# 等高图
import matplotlib.pyplot as plt
import numpy as np

def f(x,y): # 计算点(x,y)处的高度
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)

n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)

X,Y = np.meshgrid(x,y)

# use plt.contourf to filling contours
# X,Y and value for (X,Y) point

plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)# 8 是分成几个高度

# use plt.contour to add contour lines  contour:等高线
C = plt.contour(X,Y,f(X,Y),8,color='black',linewidth=0.5)

# adding label
plt.clabel(C,inline=True,fontsize=10) # 标签在线里面

plt.show()

猜你喜欢

转载自www.cnblogs.com/zpcoding/p/9721335.html