意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

使用matplotlib绘图的基本知识和技巧有哪些

来源:恒创科技 编辑:恒创科技编辑部
2023-12-29 18:25:59
这篇文章给大家分享的是使用matplotlib绘图的基本知识和技巧有哪些。小编觉得挺实用的,因此分享给大家做个参考,文中的介绍得很详细,而要易于理解和学习,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。

测试环境:

Jupyter QtConsole 4.2.1
Python 3.6.1


使用matplotlib绘图的基本知识和技巧有哪些

1. 基本画线:

以下得出红蓝绿三色的点

import numpy as np
import matplotlib.pyplot as plt

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

以下设置线宽,得到比较粗一点儿的线,如果 plot中只给了一维信息,

默认图形是把数值匹配成纵坐标的

x = np.arange(0., 5., 0.1)
plt.plot(x, 4*x, linewidth=8.0)
plt.show()

以下得到同一个图中两幅分图:

import numpy as np
import matplotlib.pyplot as plt

def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)#表示两幅图竖着排列
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)#如果为(221)和(222)表示横排列
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

2. 画直方图

以下为正态分布

np.random.seed(19680801)

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.1)


plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

其中

n, bins, patches = plt.hist(arr, bins=10, normed=0, facecolor='black', edgecolor='black',alpha=1,histtype='bar')

hist的参数非常多,但常用的就这六个,只有第一个是必须的,后面四个可选

arr: 需要计算直方图的一维数组

bins: 直方图的柱数,可选项,默认为10

normed: 是否将得到的直方图向量归一化。默认为0

facecolor: 直方图颜色

edgecolor: 直方图边框颜色

alpha: 透明度

histtype: 直方图类型,‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’

返回值 :

n: 直方图向量,是否归一化由参数normed设定

bins: 返回各个bin的区间范围

patches: 返回每个bin里面包含的数据,是一个list

3. 特殊符号和标注

用以下方式可以写出特殊的数学公式符号:

plt.title(r'$\sigma_i=15$')

以下代码表示文字显示区域是
(3, 1.5)指向坐标位置是(2,1)
import numpy as np import matplotlib.pyplot as plt ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = plt.plot(t, s, lw=2) plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), )#shrink表示箭头缩放情况,值越小显示越大
plt.ylim(-2,2)#表示y坐标轴的上界和下界 plt.show()

关于“使用matplotlib绘图的基本知识和技巧有哪些”就介绍到这了,如果大家觉得不错可以参考了解看看,如果想要了解更多,欢迎关注恒创科技,小编每天都会为大家更新不同的知识。
上一篇: python调用接口的实现是怎样的,有几种方式 下一篇: Python中单链表的数据常见操作及实现是什么