绘图和可视化(matplotlib)

《Python for Data Analysis》介绍如何利用matplotlib进行数据可视化,包括创建图表、调整子图间距、设置颜色、标记和线型,以及添加刻度、标签、图例和注解等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《Python for Data Analysis》

绘图和可视化是数据分析中的一项重要工作。通过可视化,能够更好的观察数据的模式,帮助我们找出数据的异常值、必要的数据转换、得出有关模型的想法。

matplotlib

用法:

  • 在ipython中,使用ipython --pylab模式启动;

  • 或jupyter notebook中,%matplotlib inline (better!)

In [1]: import numpy as np
   ...: data = np.arange(10)
   ...: data
   ...: plt.plot(data)
   ...:
Out[1]: [<matplotlib.lines.Line2D at 0x70b6c18>]

这里写图片描述

Figure对象

In [3]: fig = plt.figure()

In [4]: ax1 = fig.add_subplot(2, 2, 1)

In [5]: ax2 = fig.add_subplot(2, 2, 2)
   ...: ax3 = fig.add_subplot(2, 2, 3)
   ...:

In [6]: plt.plot(np.random.randn(50).cumsum(), 'k--')
Out[6]: [<matplotlib.lines.Line2D at 0xe404ba8>]

这里写图片描述

subplots方法

创建一个新的Figure对象,并返回一个含有已创建的subplot对象的Numpy数组。

In [7]: fig, axes = plt.subplots(2, 3)
   ...: axes
   ...:
Out[7]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E363588>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000000E598198>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000000E693B00>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E6F67F0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000000E8065F8>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x000000000E851EB8>]], dtype=object)

这里写图片描述

参数选项
nrowssubplot的行数
ncolssubplot的列数
sharex所有subplot使用相同的X轴刻度(调节xlim会影响所有subplot)
sharey共享Y轴刻度
subplot_kw用于创建各subplot的关键字字典
**fig_kw创建figure的其他关键字,如plot.subplots(2,2,figuresize=(8,6))

调整subplot周围的间距:subplots_adjust方法

subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

In [8]: fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
   ...: for i in range(2):
   ...:     for j in range(2):
   ...:         axes[i, j].hist(np.random.randn(500), bins=50, color='k', alpha=0.5)
   ...: plt.subplots_adjust(wspace=0, hspace=0)
   ...:

这里写图片描述

颜色、标记和线型

In [9]: plt.figure()
   ...: from numpy.random import randn
   ...: plt.plot(randn(30).cumsum(), 'ko--')
   ...:
Out[9]: [<matplotlib.lines.Line2D at 0x10c49b00>]

这里写图片描述

In [10]: data = np.random.randn(30).cumsum()
    ...: plt.plot(data, 'k--', label='Default')
    ...: plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')
    ...: plt.legend(loc='best')
    ...:
Out[10]: <matplotlib.legend.Legend at 0x10dd6ef0>

这里写图片描述

刻度、标签和图例

In [11]: fig = plt.figure()
    ...: ax = fig.add_subplot(1, 1, 1)
    ...: ax.plot(np.random.randn(1000).cumsum())
    ...: ticks = ax.set_xticks([0, 250, 500, 750, 1000])
    ...: labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
    ...:                             rotation=30, fontsize='small')
    ...: ax.set_title('My first matplotlib plot')
    ...: ax.set_xlabel('Stages')
    ...:
Out[11]: <matplotlib.text.Text at 0x10e6c3c8>

这里写图片描述

In [12]: from numpy.random import randn
    ...: fig = plt.figure(); ax = fig.add_subplot(1, 1, 1)
    ...: ax.plot(randn(1000).cumsum(), 'k', label='one')
    ...: ax.plot(randn(1000).cumsum(), 'k--', label='two')
    ...: ax.plot(randn(1000).cumsum(), 'k.', label='three')
    ...: ax.legend(loc='best')
    ...:
Out[12]: <matplotlib.legend.Legend at 0x111d06d8>

这里写图片描述

注解以及在Subplot上绘图

from datetime import datetime

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

data = pd.read_csv('examples/spx.csv', index_col=0, parse_dates=True)
spx = data['SPX']

spx.plot(ax=ax, style='k-')

crisis_data = [
    (datetime(2007, 10, 11), 'Peak of bull market'),
    (datetime(2008, 3, 12), 'Bear Stearns Fails'),
    (datetime(2008, 9, 15), 'Lehman Bankruptcy')
]

for date, label in crisis_data:
    ax.annotate(label, xy=(date, spx.asof(date) + 75),
                xytext=(date, spx.asof(date) + 225),
                arrowprops=dict(facecolor='black', headwidth=4, width=2,
                                headlength=4),
                horizontalalignment='left', verticalalignment='top')

# Zoom in on 2007-2010
ax.set_xlim(['1/1/2007', '1/1/2011'])
ax.set_ylim([600, 1800])

ax.set_title('Important dates in the 2008-2009 financial crisis')

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值