Python 各种画图

简介: Python 各种画图

Python 各种画图

一、基础知识
1、常用语句
2、线型 + 符号 + 颜色
3、图例使用
二、画图样例
1、散点图
2、柱状图
3、折线图
4、概率分布直方图
5、累计概率分布曲线
6、概率分布直方图+累计概率分布图
说实话,Python 画图和 Matlab 画图十分相似【Matlab 转战 Python】
Legend 图例:https://blog.csdn.net/HHG20171226/article/details/101302645
网格线设置:https://blog.csdn.net/weixin_41789707/article/details/81035997
字体设置:https://blog.csdn.net/HsinglukLiu/article/details/107821714

一、基础知识
1、常用语句
下面是一些基本的绘图语句:

import matplotlib.pyplot as plt # 导入模块

plt.style.use('ggplot') # 设置图形的显示风格
fig=plt.figure(1) # 新建一个 figure1
fig=plt.figure(figsize=(12,6.5),dpi=100,facecolor='w')
fig.patch.set_alpha(0.5) # 设置透明度为 0.5
font1 = {'weight' : 60, 'size' : 10} # 创建字体,设置字体粗细和大小
ax1.set_xlim(0,100) # 设置 x 轴最大最小刻度
ax1.set_ylim(-0.1,0.1) # 设置 y 轴最大最小刻度
plt.xlim(0,100) # 和上面效果一样
plt.ylim(-1,1)
ax1.set_xlabel('X name',font1) # 设置 x 轴名字
ax1.set_ylabel('Y name',font1) # 设置 y 轴名字
plt.xlabel('aaaaa') # 设置 x 轴名字
plt.ylabel('aaaaa') # 设置 y 轴名字
plt.grid(True) # 增加格网
plt.grid(axis="y") # 只显示横向格网
plt.grid(axis="x") # 只显示纵向格网
ax=plt.gca() # 获取当前axis,
fig=plt.gcf() # 获取当前figures
plt.gca().set_aspect(1) # 设置横纵坐标单位长度相等
plt.text(x,y,string) # 在 x,y 处加入文字注释
plt.gca().set_xticklabels(labels, rotation=30, fontsize=16) # 指定在刻度上显示的内容
plt.xticks(ticks, labels, rotation=30, fontsize=15) # 上面两句合起来
plt.legend(['Float'],ncol=1,prop=font1,frameon=False) # 设置图例 列数、去掉边框、更改图例字体
plt.title('This is a Title') # 图片标题
plt.show() # 显示图片,没这行看不见图
plt.savefig(path, dpi=600) # 保存图片,dpi可控制图片清晰度
plt.rcParams['font.sans-serif'] = ['SimHei'] # 添加这条可以让图形显示中文
mpl.rcParams['axes.unicode_minus'] = False # 添加这条可以让图形显示负号
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none') #设置图片的右边框和上边框为不显示

子图

ax1=plt.subplot(3,1,1)
ax1.scatter(time,data[:,1],s=5,color='blue',marker='o') # size, color, 标记
ax1=plt.subplot(3,1,2)
...

设置坐标刻度朝向,暂未成功

plt.rcParams['xtick.direction'] = 'in'
ax = plt.gca()
ax.invert_xaxis()
ax.invert_yaxis()
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
2、线型 + 符号 + 颜色
https://blog.csdn.net/Gou_Hailong/article/details/121787030

3、图例使用
https://blog.csdn.net/Gou_Hailong/article/details/121795267

二、画图样例
不要忘记 import plt

import matplotlib.pyplot as plt
1
1、散点图
years = [2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]
turnovers = [0.5, 9.36, 52, 191, 350, 571, 912, 1027, 1682, 2135, 2684]
plt.figure()
plt.scatter(years, turnovers, c='red', s=100, label='legend')
plt.xticks(range(2008, 2020, 3))
plt.yticks(range(0, 3200, 800))
plt.xlabel("Year", fontdict={'size': 16})
plt.ylabel("number", fontdict={'size': 16})
plt.title("Title", fontdict={'size': 20})
plt.legend(loc='best')
plt.show()
1
2
3
4
5
6
7
8
9
10
11

2、柱状图
X=[1,2,3,4,5]
Y=[0.2,0.6,0.1,0.8,0.4]
plt.bar(X,Y,color='b')
plt.show()
1
2
3
4

3、折线图
参考:https://blog.csdn.net/AXIMI/article/details/99308004

plt.rcParams['font.sans-serif'] = ['SimHei'] # 添加这条可以让图形显示中文
x_axis_data = [1, 2, 3, 4, 5]
y_axis_data = [1, 2, 3, 4, 5]

plot中参数的含义分别是横轴值,纵轴值,线的形状,颜色,透明度,线的宽度和标签

plt.plot(x_axis_data, y_axis_data, 'ro-', color='#4169E1', alpha=0.8, linewidth=1, label='一些数字')

显示标签,如果不加这句,即使在plot中加了label='一些数字'的参数,最终还是不会显示标签

plt.legend(loc="upper right")
plt.xlabel('x轴数字')
plt.ylabel('y轴数字')
plt.show()
1
2
3
4
5
6
7
8
9
10

4、概率分布直方图
主要通过函数plt.hist()来实现,

matplotlib.pyplot.hist(
x, bins=10, range=None, normed=False,edgecolor='k',
weights=None, cumulative=False, bottom=None,
histtype=u'bar', align=u'mid', orientation=u'vertical',
rwidth=None, log=False, color=None, label=None, stacked=False,
hold=None, **kwargs)
1
2
3
4
5
6
其中,常用的参数及其含义如下:

bins:“直方条”的个数,一般可取20
range=(a,b):只考虑区间(a,b)之间的数据,绘图的时候也只绘制区间之内的
edgecolor=‘k’:给直方图加上黑色边界,不然看起来很难看(下面的例子就没加,所以很难看)
example_list=[]
n=10000
for i in range(n):

tmp=[np.random.normal()]
example_list.extend(tmp)

width=100
n, bins, patches = plt.hist(example_list,bins = width,color='blue',alpha=0.5)
X = bins[0:width]+(bins[1]-bins[0])/2.0
Y = n
maxn=max(n)
maxn1=int(maxn%8+maxn+8*2)
ydata=list(range(0,maxn1+1,maxn1//8))
yfreq=[str(i/sum(n)) for i in ydata]
plt.plot(X,Y,color='green') #利用返回值来绘制区间中点连线
p1 = np.polyfit(X, Y, 7) #利用7次多项式拟合,返回拟多项式系数,按照阶数从高到低排列
Y1 = np.polyval(p1,X)
plt.plot(X,Y1,color='red')
plt.xlim(-2.5,2.5)
plt.ylim(0)
plt.yticks(ydata,yfreq) #这条语句控制纵坐标是频数或频率,打开是频率,否则是频数
plt.legend(['midpoint','fitting'],ncol=1,frameon=False)
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

上面的图片中,绿线是直方图矩形的中点连线,红线是根据直方图的中点7次拟合的曲线。

5、累计概率分布曲线
累积分布函数(Cumulative Distribution Function),又叫分布函数,是概率密度函数的积分,能完整描述一个实随机变量X的概率分布。

example_list=[]
n=10000
for i in range(n):

tmp=[np.random.normal()]
example_list.extend(tmp)

width=50
n, bins, patches = plt.hist(example_list,bins = width,color='blue',alpha=0.5)
plt.clf() # clear the figure
X = bins[0:width]+(bins[1]-bins[0])/2.0
bins=bins.tolist()
freq=[f/sum(n) for f in n]
acc_freq=[]
for i in range(0,len(freq)):

if i==0:
    temp=freq[0]
else:
    temp=sum(freq[:i+1])
acc_freq.append(temp)

plt.plot(X,acc_freq,color='r') # Cumulative probability curve
yt=plt.yticks()
yt1=yt[0].tolist()
def to_percent(temp,position=0): # convert float number to percent

return '%1.0f'%(100*temp) + '%'

ytk1=[to_percent(i) for i in yt1 ]
plt.yticks(yt1,ytk1)
plt.ylim(0,1)
plt.show()
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

6、概率分布直方图+累计概率分布图
参考:https://blog.csdn.net/qq_38412868/article/details/105319818
可以绘制概率分布直方图和累计概率曲线

笔者进行了一些的改编:

def draw_cum_prob_curve(data,bins=20,title='Distribution Of Errors',xlabel='The Error(mm)',pic_path=''):

"""
plot Probability distribution histogram and Cumulative probability curve.

> @param[in] data:          The error data
> @param[in] bins:          The number of hist
> @param[in] title:         The titile of the figure
> @param[in] xlabel:        The xlable name
> @param[in] pic_path:      The path where you want to save the figure
return:     void
"""
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.ticker import FuncFormatter
from matplotlib.pyplot import MultipleLocator
def to_percent(temp,position=0):          # convert float number to percent
    return '%1.0f'%(100*temp) + '%'
fig, ax1 = plt.subplots(1, 1, figsize=(12, 6), dpi=100, facecolor='w')
font1 = {'weight': 600, 'size': 15}

n, bins, patches=ax1.hist(data,bins =bins, alpha = 0.65,edgecolor='k') # Probability distribution histogram
yt=plt.yticks()
yt1=yt[0].tolist()
yt2=[i/sum(n) for i in yt1]
ytk1=[to_percent(i) for i in yt2 ]
plt.yticks(yt1,ytk1)
X=bins[0:-1]+(bins[1]-bins[0])/2.0 
bins=bins.tolist()
freq=[f/sum(n) for f in n]
acc_freq=[]
for i in range(0,len(freq)):
    if i==0:
        temp=freq[0]
    else:
        temp=sum(freq[:i+1])
    acc_freq.append(temp)
ax2=ax1.twinx()                         # double ylable
ax2.plot(X,acc_freq)                    # Cumulative probability curve
ax2.yaxis.set_major_formatter(FuncFormatter(to_percent))
ax1.set_xlabel(xlabel,font1)
ax1.set_title(title,font1)
ax1.set_ylabel('Frequency',font1)
ax2.set_ylabel("Cumulative Frequency",font1)
#plt.savefig(pic_path,format='png', dpi=300)

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
调用示例:

example_list=[]
n=10000
for i in range(n):

tmp=[np.random.normal()]
example_list.extend(tmp)

tit='TEST'
xla='DATA'
draw_cum_prob_curve(example_list,50,tit,xla)
plt.show()

目录
相关文章
|
5月前
|
算法 Python
关联规则算法及其画图(python
关联规则算法及其画图(python
64 2
|
5月前
|
数据可视化 API Python
画图实战-Python实现某产品全年销量数据多种样式可视化
画图实战-Python实现某产品全年销量数据多种样式可视化
79 0
|
7天前
|
Python
pyecharts:一款python画图神器
pyecharts:一款python画图神器
17 0
|
5月前
|
Python
python 海龟画图tutle螺旋线
python 海龟画图tutle螺旋线
113 0
|
5月前
|
存储 Python
【python】——超市管理系统和用turtle动态画图(爱心和魔幻曲线)
【python】——超市管理系统和用turtle动态画图(爱心和魔幻曲线)
【python】——超市管理系统和用turtle动态画图(爱心和魔幻曲线)
|
5月前
|
Python
python画图中文乱码
python画图中文乱码
34 0
|
数据处理 Python
技巧 | Python画图辅助标注(多子图共坐标轴)
技巧 | Python画图辅助标注(多子图共坐标轴)
技巧 | Python画图辅助标注(多子图共坐标轴)
|
数据可视化 Python
Python版 孤勇者 | 画图+演奏+音乐可视化
另外还有个叫做 pgzero 的游戏开发库,里面有一个可以播放音符的方法。
Python版 孤勇者 | 画图+演奏+音乐可视化
|
计算机视觉 Python
Python随机游走轨迹模拟(带画图)
Python随机游走轨迹模拟(带画图)
217 0
|
人工智能 前端开发 数据处理
Python实现画图软件功能
Python实现画图软件功能
102 0
下一篇
无影云桌面