Mrli
别装作很努力,
因为结局不会陪你演戏。
Contacts:
QQ博客园

matplotlib.pyplot使用

2019/12/11 Python
Word count: 1,650 | Reading time: 9min

matplotlib.pyplot使用

注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
## 方法一
####################
for x_value,y_value in zip(x,y):
plt.text(x_value,y_value,y_value,fontsize= 15) #文字标注(x,y,值)
####################

## 方法二
####################
for xy in zip(x, y):
plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points')

x0 = 1
y0 = 2* x0
plt.annotate(r'${}+{}={}$'.format(x0,x0,y0),xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords = 'offset points',
fontsize=16,arrowprops=dict(
arrowstyle='->',
connectionstyle='arc3,rad=.2'
))
####################

# 添加注释(annotate),参数说明
plt.annotate(r'$2x+1={}$'.format(y),xy=(x,y),xycoords='data',xytext=(+30,-30),textcoords = 'offset points',fontsize=16,
arrowprops=dict(
arrowstyle='->',
connectionstyle='arc3,rad=.2')
)

# 第一个参数是注释的内容
# xy设置箭头尖的坐标
# xytext设置注释内容显示的起始位置
# arrowprops 用来设置箭头
# facecolor 设置箭头的颜色
# headlength 箭头的头的长度
# headwidth 箭头的宽度
# width 箭身的宽度

坐标轴转移

1
2
3
4
5
6
7
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

图形类型

  • 散列图 ax1.scatter(x,y,c = 'r',marker = 'o')
  • 折线图plt.plot()
  • 直方图plt.hist()
  • 条形图plt.bar(left=index,height=y,color='green',width=0.5)
  • 饼状图:plt.pie(x=fracs,labels=labels,autopct='%.0f%%',explode=explode)#autopct显示百分比
  • 箱形图plt.boxplot(data,labels=labels)
  • 等高线 plt.contourf(X,Y,f(X,Y),8,alpha = .75,cmap = plt.cm.hot)

scatter基本的用法

条形图

1
2
3
4
5
6
7
8
9
fig = plt.figure(dpi=256, figsize=(10, 8))
plt.plot(U,I,'r*')
plt.xlabel('U(V)',fontsize=10)
plt.ylabel('I(10e-9A)',fontsize=10)
plt.title('The line chart of the relation between U and I',fontsize=15)
plt.ylim(0,max(I)+0.5)

x = np.linspace(0,max(I)+0.5,40)
plt.yticks(x,fontsize=6)

线条选项

1
2
plt.plot(x,y,'r*') # 默认为蓝色
# 等价于plt.plot(x,y,color= 'r', marker ='*')

散点图

1
2
3
4
5
6
7
8
n =100
X = np.random.normal(0,10,n)
Y = np.random.normal(0,10,n)
T = np.arctan2(Y,X)
plt.scatter(X,Y,c= T,s=6)
plt.xticks(())
plt.yticks(())
plt.show()

柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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='#9999ff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
for x,y in zip(X,Y1):
plt.text(x+0,y+0.05,"%.2f" %y,ha='center',va='bottom')
# horizontal alignment , vertical alignment
plt.xlim(-.5,n)
plt.xticks(())
plt.ylim(-1.25,1.25)
plt.yticks(())
plt.show()

等高线

1
2
3
4
5
6
7
8
9
10
11
12
def f(x,y):
# return 1 + 1/x**3 + y**5
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)

plt.contourf(X,Y,f(X,Y),8,alpha = .75 , cmap = plt.cm.hot)
C = plt.contour(X,Y,f(X,Y),8,colors = 'black')
plt.clabel(C,inline = True,fontsize = 10)

图例

1
2
3
l1 , = plt.plot(x,y,linestyle= '--',color = 'red',linewidth=2.0)
# 返回值为一个元组
plt.legend(handles=[l1],labels = ['les'],loc='best')

3D图形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
x = np.linspace(-4,4,50)
y = np.linspace(-4,4,50)
X,Y = np.meshgrid(x,y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap = plt.get_cmap('rainbow'))
ax.contour(X,Y,Z,zdir='x',offset = -5)#画等高线图,往哪个(x)轴压缩,到x=-5位置
plt.show()

分格画子图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# method 1: subplot2grid
##########################
plt.figure()
axl=plt. subplot2grid((3,3),(0,0), colspan=3, rowspan=1)
# 三行三列, 从源点(0,0)开始画,第一张图占一行三列
axl.plot([1,2],[1,2])
ax1.set_title('xxx')
# 原来plt.title()设置的方法,现在都变成了ax?.set_xxx,多了前缀set_
ax2=plt. subplot2grid((3,3),(1,0), colspan=2,)
ax3=plt. subplot2grid((3,3),(1,2), rowspan=2)
ax4=plt. subplot2grid((3,3),(2,0)

#method 2 :gridspec
import matplotlib.gridspec as gridspecc
plt.figure()
gs=gridspec.GridSpec(3,3)
ax1=plt.subplot(gs[0, :])
ax2=plt.subplot(gs[1, :2])
ax3=plt.subplot(gs[1: ,2])
ax4=plt.subplot(gs[-1,0])
ax5=plt.subplot(gs[-1,-2])

附录:

温习源自WeiboSpider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Cgraph(object):
def __init__(self):
self.db = db
self.create_dir()
self.Start_timestmp = time.mktime(time.strptime('2018-7-5 00:00','%Y-%m-%d %H:%M'))


def judge_over(self, _time): # start_time is timestamp
'''
判断时间是否已经超过预设时间
:param Start_timestmp:
:param _time:
:return:
'''
timestamp = time.mktime(time.strptime(_time, '%Y-%m-%d %H:%M'))
# Start_timestamp = time.mktime(time.strptime(Start_time,'%Y-%m-%d %H:%M'))
if timestamp - self.Start_timestmp < 0:
return True
else:
return False

def create_dir(self):
if not os.path.isdir('.\\graph'):
os.makedirs('.\\graph')


def count(self,lists):
exist_dict = OrderedDict()
for x in lists:
if x not in exist_dict:
exist_dict[x] = 1
else:
exist_dict[x] += 1
return dict(sorted(exist_dict.items(),key=lambda x:x[0]))


def unify_time(self,_time):
c = _time.split('-')
_time = '-'.join(['0' + x if len(x.strip()) == 1 else x for x in c])
if _time[:4] == '2018':
_time = _time[5:10]
return _time[:10]


def Draw(self):
timelist = []
for alls in self.db.find():
if alls.get('time'):
print(alls.get('time'))
timelist.append(self.unify_time(alls.get('time')))

infodict = self.count(timelist[::-1])
plt.figure(figsize=(40, 18)) #设置图片大小
# plt.rcParams['figure.figsize'] = (40.0, 12.0) 设置图片大小的另外一种方法
# plt.rcParams['figure.dpi'] = 400
x = list(infodict.keys())
y = list(infodict.values())
plt.plot(x,y,linewidth=2,color='r',marker='o',markersize=8)
for x_value,y_value in zip(x,y):
plt.text(x_value,y_value,y_value,fontsize= 15) #文字标注(x,y,值)
plt.ylim((0, max(y))) #纵坐标y的上下限
plt.yticks([x for x in range(0,max(y)+10,10)]) #y的比例尺
plt.xlabel('Time')
plt.ylabel('Keyword times') #y轴的标签
plt.title('Weibo Keyword\'s Trendency') #图的标题
plt.savefig('.\\graph\\{}.jpg'.format(TABLE)) #保存图片
plt.clf()


if __name__ == '__main__':
graph = Cgraph()
graph.Draw()
print('完成')

使用:大物实验画折线图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import csv
from matplotlib import pyplot as plt
import os
import numpy as np
I = []
U = []
def extractFromCsv(filename):
with open(filename,'r') as f:
reader = csv.reader(f)
for row in reader:
if reader.line_num == 1: #跳过表头
continue
U.append(float(row[0]))
I.append((float(row[1])))

def drawPic(filename):
fig = plt.figure(dpi=256, figsize=(10, 8))
plt.plot(U,I,'r*')
plt.xlabel('U(V)',fontsize=10)
plt.ylabel('I(10e-9A)',fontsize=10)
plt.title('The line chart of the relation between U and I',fontsize=15)
plt.ylim(0,max(I)+0.5)

x = np.linspace(0,max(I)+0.5,40)
plt.yticks(x,fontsize=6)

if not os.path.exists(".\\graph"):
os.mkdir('.\\graph')
plt.savefig('.\\graph\\{}.jpg'.format(filename))

if __name__ == "__main__":
filename='phy.csv'
extractFromCsv(filename)
drawPic(filename)

参考:

matplotlib 画图颜色参数值及对应色卡

matplotlib绘图总结——对画图句柄的操作

matplotlib中plt.scatter()参数详解——很详细

Author: Mrli

Link: https://nymrli.top/2018/11/10/matplotlib-pyplot使用/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
二分搜索降低时间复杂度
NextPost >
apt代理的设置
CATALOG
  1. 1. matplotlib.pyplot使用
    1. 1.1. 注释
    2. 1.2. 坐标轴转移
    3. 1.3. 图形类型
      1. 1.3.1. 条形图
        1. 1.3.1.1. 线条选项
      2. 1.3.2. 散点图
      3. 1.3.3. 柱状图
      4. 1.3.4. 等高线
    4. 1.4. 图例
    5. 1.5. 3D图形
      1. 1.5.1.
    6. 1.6. 分格画子图
    7. 1.7. 附录:
      1. 1.7.1. 温习源自WeiboSpider
      2. 1.7.2. 使用:大物实验画折线图
    8. 1.8. 参考: