美文网首页
使用matplotlib绘制数据图

使用matplotlib绘制数据图

作者: KoooOooooK | 来源:发表于2019-07-26 11:15 被阅读0次

使用python的绘图包matplotlib绘制如下的一张数据图


首先是导入包

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import cm as cm

其中,matplotlib包是用来绘图的,而numpy包则是准备数据的。

# 基本数据
x = np.linspace(0.5, 3.5, 100)
y = np.sin(x)
y1 = np.random.randn(100)

0x00 先绘制点图

plt.scatter(x, y1, c='0.25', label='scatter figure')

得到如下效果:


0x01 绘制线图

plt.plot(x, y, ls='--', lw=2, label='plot figure')

得到如下效果:


0x02 轴框设置

通过设置,只保留左边和右边的轴。

for spine in plt.gca().spines.keys():
    if spine == 'top' or spine == 'right':
        plt.gca().spines[spine].set_color('none')

plt.gca().xaxis.set_ticks_position('bottom')
plt.gca().yaxis.set_ticks_position('left')

效果如下:


0x03 设置x轴和y轴的区间

plt.xlim(0.0, 4.0)
plt.ylim(-3.0, 3.0)

0x04 设置x轴和y轴的标签

plt.xlabel('x_axis')
plt.ylabel('y_axis')

0x05 设置网格、轴线和覆盖区域

plt.grid(True, ls=':', c='r')

plt.axhline(y=0.0, c='r', ls='--', lw=2)

plt.axvspan(xmin=1.0, xmax=2.0, facecolor='y', alpha=.3)

0x06 设置注释、标题和说明

plt.annotate('maximum', 
            xy=(np.pi/2, 1.0), 
            xytext=((np.pi/2)+0.15, 1.5), 
            weight='bold', 
            color='r', 
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r'))

plt.annotate('spines', 
            xy=(0.75, -3), 
            xytext=(0.35, -2.25), 
            weight='bold', 
            color='b', 
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='b'))

plt.annotate('', 
            xy=(0, -2.78), 
            xytext=(0.4, -2.32), 
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='b'))
            
plt.annotate('', 
            xy=(3.5, -2.98), 
            xytext=(3.6, -2.70), 
            arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='b'))
            
plt.text(3.6, -2.70, "'|' is tickline", weight='bold', color='b')
plt.text(3.6, -2.95, "3.5 is ticklabel", weight='bold', color='b')

plt.title('structure of matplotlib')

plt.legend(loc='upper right')

完成。

相关文章

网友评论

      本文标题:使用matplotlib绘制数据图

      本文链接:https://www.haomeiwen.com/subject/awdrrctx.html