绘图和可视化
matplotlib的示例库和文档是成为绘图高手的最佳学习资源。
import numpy as np
import pandas as pd
from pandas import DataFrame,Series
#画图所需
%pylab inline
%matplotlib inline
import matplotlib.pyplot as plt
Populating the interactive namespace from numpy and matplotlib
plot(np.arange(10))
Figure和Subplot
Subplot画图有问题,无法在一个框内显示多幅图。(fig.add_subplot(2,2,2))
但是,plt.subplots就可以了
fig = plt.figure()
<Figure size 432x288 with 0 Axes>
#图像应该是2*2的,且当前选中的是4个subplot中的第一个
ax1 = fig.add_subplot(2,2,1)
#把后面两个subplot创建出来
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax1
<AxesSubplot:>
from numpy.random import randn
plt.plot(randn(50).cumsum(), 'k--')#黑色虚线
plt.scatter(np.arange(30),np.arange(30)+3*randn(30))
plt.hist(randn(100),bins=20, color='k', alpha=0.3)
(array([ 2., 1., 3., 7., 5., 9., 14., 13., 9., 5., 3., 5., 9.,
7., 4., 1., 1., 1., 0., 1.]),
array([-1.73930113, -1.49690424, -1.25450736, -1.01211047, -0.76971358,
-0.5273167 , -0.28491981, -0.04252292, 0.19987396, 0.44227085,
0.68466774, 0.92706462, 1.16946151, 1.4118584 , 1.65425528,
1.89665217, 2.13904906, 2.38144595, 2.62384283, 2.86623972,
3.10863661]),
<BarContainer object of 20 artists>)
fig,axes = plt.subplots(2,3)
axes
array([[<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>],
[<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>]], dtype=object)
#有个知识点
import matplotlib.pyplot as plt
from pylab import *
img = plt.imread('pyplot.subplots的选项.png')
imshow(img)
调整subplot周围的间距
subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)
#wspace用于控制宽度和高度的百分比
<Figure size 432x288 with 0 Axes>
fig, axes = plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2):
for j in range(2):
axes[i,j].hist(randn(500),bins=50,color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0)
颜色、标记和线型
#带有标记的线型图实例
plt.plot(randn(30).cumsum(),'ko--')
刻度、标签和图例
plt.xlim([0,10])
(0.0, 10.0)
设置标题、轴标签、刻度以及刻度标签
#为了演示xticks(刻度位置)的简单线型图
fig = plt.figure();ax = fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum())
fig = plt.figure();ax = fig.add_subplot(1,1,1)
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')
ax.plot(randn(