python_画图

利用Python进行数据分析(第二版).pdf

Plotting and Visualization
import numpy as np
import pandas as pd
PREVIOUS_MAX_ROWS = pd.options.display.max_rows
pd.options.display.max_rows = 20
np.random.seed(12345)
import matplotlib.pyplot as plt
import matplotlib
plt.rc('figure', figsize=(10, 6))
np.set_printoptions(precision=4, suppress=True)
%matplotlib notebook

A Brief matplotlib API Primer
# 绘制折线图
# 1.4.4 matplotlib
# matplotlib 是 Python 主要的科学绘图库,其功能为生成可发布的可视化内容,如折
# 线图、直方图、散点图等。将数据及各种分析可视化,可以让你产生深刻的理解,而
# 我们将用 matplotlib 完 成 所 有 的 可 视 化 内 容。 在 Jupyter Notebook 中, 你 可 以 使 用
# %matplotlib notebook 和 %matplotlib inline 命令,将图像直接显示在浏览器中。我们推
# 荐使用 %matplotlib notebook 命令,它可以提供交互环境(虽然在写作本书时我们用的是
# %matplotlib inline)。举个例子,下列代码会生成图 1-1 中的图像:
%matplotlib inline
import matplotlib.pyplot as plt

# Generate a sequence numbers from -10 to 10 with 100 steps in between
# 在-10和10之间生成一个数列,共100个数
x = np.linspace(-10, 10, 100)
# create a second array using sinus
y = np.sin(x)
# plot函数绘制一个数组关于另一个数组的折线图
# The plot function makes a line chart of one array against another
plt.plot(x, y, marker="x")



import matplotlib.pyplot as plt
import numpy as np
data = np.arange(10)
data
plt.plot(data)
[<matplotlib.lines.Line2D at 0x2093329d7b8>]

Figures and Subplots
fig = plt.figure()
<Figure size 432x288 with 0 Axes>
# 图像应该是2×2的(即最多4张图),且当前    画方块图
# 选中的是4个subplot中的第⼀个(编号从1开始)
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook\deprecation.py:107: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  warnings.warn(message, mplDeprecation, stacklevel=1)
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)

fig = plt.figure() ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3)

# "k--"是⼀个线型选项,⽤于告诉matplotlib绘制⿊⾊虚线图。上⾯
# 那些由fig.add_subplot所返回的对象是AxesSubplot对象
plt.plot(np.random.randn(50).cumsum(), 'k--')
[<matplotlib.lines.Line2D at 0x209349077b8>]

_ = ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))
<matplotlib.collections.PathCollection at 0x20934c55b38>
plt.close('all')
# 创建包含subplot⽹格的figure是⼀个⾮常常⻅的任务,matplotlib
# 有⼀个更为⽅便的⽅法plt.subplots,它可以创建⼀个新的
# Figure,并返回⼀个含有已创建的subplot对象的NumPy数组:
fig, axes = plt.subplots(2, 3)
axes
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x0000020934AB87F0>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000020934B39748>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000020934B60D68>],
       [<matplotlib.axes._subplots.AxesSubplot object at 0x0000020934B92438>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000020934BB9B00>,
        <matplotlib.axes._subplots.AxesSubplot object at 0x0000020934BEC198>]],
      dtype=object)

Adjusting the spacing around subplots
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

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)

# 调整subplot周围的间距
# 默认情况下,matplotlib会在subplot外围留下⼀定的边距,并在
# subplot之间留下⼀定的间距。间距跟图像的⾼度和宽度有关,因
# 此,如果你调整了图像⼤⼩(不管是编程还是⼿⼯),间距也会
# ⾃动调整。利⽤Figure的subplots_adjust⽅法可以轻⽽易举地修
# 改间距,此外,它也是个顶级函数:\
# 柱形图
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)
# wspace和hspace⽤于控制宽度和⾼度的百分⽐

Colors, Markers, and Line Styles
ax.plot(x, y, 'g--')

ax.plot(x, y, linestyle='--', color='g')

颜⾊、标记和线型
# matplotlib的plot函数接受⼀组X和Y坐标,还可以接受⼀个表示颜
# ⾊和线型的字符串缩写。例如,要根据x和y绘制绿⾊虚线
# 颜⾊、标记和线型
# matplotlib的plot函数接受⼀组X和Y坐标,还可以接受⼀个表示颜
# ⾊和线型的字符串缩写。例如,要根据x和y绘制绿⾊虚线
plt.figure()
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
折线图
#折线图
from numpy.random import randn
plt.plot(randn(30).cumsum(), 'ko--')
[<matplotlib.lines.Line2D at 0x20934e970f0>]

plot(randn(30).cumsum(), color='k', linestyle='dashed', marker='o')

plt.close('all')
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')
<matplotlib.legend.Legend at 0x209350faf28>

Ticks, Labels, and Legends
Setting the title, axis labels, ticks, and ticklabels
刻度、标签和图例
# 对于⼤多数的图表装饰项,其主要实现⽅式有⼆:使⽤过程型的
# pyplot接⼝(例如,matplotlib.pyplot)以及更为⾯向对象的原⽣
# matplotlib API。
# 刻度、标签和图例
# 对于⼤多数的图表装饰项,其主要实现⽅式有⼆:使⽤过程型的
# pyplot接⼝(例如,matplotlib.pyplot)以及更为⾯向对象的原⽣
# matplotlib API。
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())
[<matplotlib.lines.Line2D at 0x20935166710>]

# 要改变x轴刻度,最简单的办法是使⽤set_xticks和
# set_xticklabels。
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
                            rotation=30, fontsize='small')
# rotation选项设定x刻度标签倾斜30度。最后,再⽤set_xlabel为X
# 轴设置⼀个名称,并⽤set_title设置⼀个标题
ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')
Text(0.5,3.2,'Stages')
props = { 'title': 'My first matplotlib plot', 'xlabel': 'Stages' } ax.set(**props)

Adding legends
# 添加图例
# 图例(legend)是另⼀种⽤于标识图表元素的重要⼯具。添加图
# 例的⽅式有多种。最简单的是在添加subplot的时候传⼊label参
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')
[<matplotlib.lines.Line2D at 0x2093523a0f0>]

​
ax.legend(loc='best')
<matplotlib.legend.Legend at 0x20935264dd8>
Annotations and Drawing on a Subplot
ax.text(x, y, 'Hello world!', family='monospace', fontsize=10)

# 注解以及在Subplot上绘图   注释
# 除标准的绘图类型,你可能还希望绘制⼀些⼦集的注解,可能是
# ⽂本、箭头或其他图形等。注解和⽂字可以通过text、arrow和
# annotate函数进⾏添加。text可以将⽂本绘制在图表的指定坐标
# (x,y),还可以加上⼀些⾃定义格式:
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')
Text(0.5,1,'Important dates in the 2008-2009 financial crisis')

ax.set_title('Important dates in the 2008–2009 financial crisis')
fig = plt.figure() ax = fig.add_subplot(1, 1, 1)

rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3) circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3) pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]], color='g', alpha=0.5)

ax.add_patch(rect) ax.add_patch(circ) ax.add_patch(pgon)

要在图表中添加⼀个图形,你需要创建⼀个块对象shp,然后通
# 过ax.add_patch(shp)将其添加到subplot中
# 要在图表中添加⼀个图形,你需要创建⼀个块对象shp,然后通
# 过ax.add_patch(shp)将其添加到subplot中
fig = plt.figure(figsize=(12, 6)); ax = fig.add_subplot(1, 1, 1)
rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],
                   color='g', alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
<matplotlib.patches.Polygon at 0x2093635ca20>

### Saving Plots to File
​
plt.savefig('figpath.svg')

plt.savefig('figpath.png', dpi=400, bbox_inches='tight')

from io import BytesIO buffer = BytesIO() plt.savefig(buffer) plot_data = buffer.getvalue()

matplotlib Configuration
plt.rc('figure', figsize=(10, 10))

font_options = {'family' : 'monospace', 'weight' : 'bold', 'size' : 'small'} plt.rc('font', **font_options)

Plotting with pandas and seaborn
Line Plots
# 9.2 使⽤pandas和seaborn绘图    线形图
# matplotlib实际上是⼀种⽐较低级的⼯具。要绘制⼀张图表,你
# 组装⼀些基本组件就⾏:数据展示(即图表类型:线型图、柱状
# 图、盒形图、散布图、等值线图等)、图例、标题、刻度标签以
# 及其他注解型信息。
plt.close('all')
# 折线图
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
s.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x20936397c50>

df = pd.DataFrame(np.random.randn(10, 4).cumsum(0),
                  columns=['A', 'B', 'C', 'D'],
                  index=np.arange(0, 100, 10))
df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x209363efdd8>

Bar Plots
# 柱状图
# plot.bar()和plot.barh()分别绘制⽔平和垂直的柱状图。这时,
# Series和DataFrame的索引将会被⽤作X(bar)或Y(barh)刻
# 度(如图9-15所示):
fig, axes = plt.subplots(2, 1)
data = pd.Series(np.random.rand(16), index=list('abcdefghijklmnop'))
data.plot.bar(ax=axes[0], color='k', alpha=0.7)
data.plot.barh(ax=axes[1], color='k', alpha=0.7)
# color='k'和alpha=0.7设定了图形的颜⾊为⿊⾊,并使⽤部分的填
# 充透明度。对于DataFrame,柱状图会将每⼀⾏的值分为⼀组,
# 并排显示,如图9-16所示:
<matplotlib.axes._subplots.AxesSubplot at 0x209369ec3c8>

np.random.seed(12348)
   堆叠
# 设置stacked=True即可为DataFrame⽣成堆积柱状图,这样每⾏
# 362的值就会被堆积在⼀起   堆叠
df = pd.DataFrame(np.random.rand(6, 4),
                  index=['one', 'two', 'three', 'four', 'five', 'six'],
                  columns=pd.Index(['A', 'B', 'C', 'D'], name='Genus'))
df
df.plot.bar()
<matplotlib.axes._subplots.AxesSubplot at 0x20936b6d940>

plt.figure()
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
stacked
df.plot.barh(stacked=True, alpha=0.5)
<matplotlib.axes._subplots.AxesSubplot at 0x20936be8dd8>

plt.close('all')
tips = pd.read_csv('examples/tips.csv')
party_counts = pd.crosstab(tips['day'], tips['size'])
party_counts
# Not many 1- and 6-person parties
party_counts = party_counts.loc[:, 2:5]
# Normalize to sum to 1
party_pcts = party_counts.div(party_counts.sum(1), axis=0)
party_pcts
party_pcts.plot.bar()
plt.close('all')
import seaborn as sns
tips['tip_pct'] = tips['tip'] / (tips['total_bill'] - tips['tip'])
tips.head()
sns.barplot(x='tip_pct', y='day', data=tips, orient='h')
plt.close('all')
sns.barplot(x='tip_pct', y='day', hue='time', data=tips, orient='h')
plt.close('all')
sns.set(style="whitegrid")


Histograms and Density Plots¶
直⽅图和密度图
# 直⽅图(histogram)是⼀种可以对值频率进⾏离散化显示的柱
# 状图。数据点被拆分到离散的、间隔均匀的⾯元中,绘制的是各
# ⾯元中数据点的数量。再以前⾯那个⼩费数据为例,通过在
# Series使⽤plot.hist⽅法
# 直⽅图和密度图
# 直⽅图(histogram)是⼀种可以对值频率进⾏离散化显示的柱
# 状图。数据点被拆分到离散的、间隔均匀的⾯元中,绘制的是各
# ⾯元中数据点的数量。再以前⾯那个⼩费数据为例,通过在
# Series使⽤plot.hist⽅法
plt.figure()
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
tips['tip_pct'].plot.hist(bins=50)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-71-3d9c33ad3223> in <module>()
----> 1 tips['tip_pct'].plot.hist(bins=50)

NameError: name 'tips' is not defined
plt.figure()
tips['tip_pct'].plot.density()
plt.figure()
comp1 = np.random.normal(0, 1, size=200)
comp2 = np.random.normal(10, 2, size=200)
values = pd.Series(np.concatenate([comp1, comp2]))
sns.distplot(values, bins=100, color='k')
Scatter or Point Plots
散布图或点图
# 点图或散布图是观察两个⼀维数据序列之间的关系的有效⼿段。
# 在下⾯这个例⼦中,我加载了来⾃statsmodels项⽬的macrodata
# 数据集,选择了⼏个变量,然后计算对数差:
# 散布图或点图
# 点图或散布图是观察两个⼀维数据序列之间的关系的有效⼿段。
# 在下⾯这个例⼦中,我加载了来⾃statsmodels项⽬的macrodata
# 数据集,选择了⼏个变量,然后计算对数差:
macro = pd.read_csv('examples/macrodata.csv')
data = macro[['cpi', 'm1', 'tbilrate', 'unemp']]
trans_data = np.log(data).diff().dropna()
trans_data[-5:]
cpi	m1	tbilrate	unemp
198	-0.007904	0.045361	-0.396881	0.105361
199	-0.021979	0.066753	-2.277267	0.139762
200	0.002340	0.010286	0.606136	0.160343
201	0.008419	0.037461	-0.200671	0.127339
202	0.008894	0.012202	-0.405465	0.042560
plt.figure()
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
可以使⽤seaborn的regplot⽅法,它可以做⼀个散布图,并
# 加上⼀条线性回归的线
# 可以使⽤seaborn的regplot⽅法,它可以做⼀个散布图,并
# 加上⼀条线性回归的线
sns.regplot('m1', 'unemp', data=trans_data)
plt.title('Changes in log %s versus log %s' % ('m1', 'unemp'))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-77-38e74ae0836c> in <module>()
      1 # 可以使⽤seaborn的regplot⽅法,它可以做⼀个散布图,并
      2 # 加上⼀条线性回归的线
----> 3 sns.regplot('m1', 'unemp', data=trans_data)
      4 plt.title('Changes in log %s versus log %s' % ('m1', 'unemp'))

NameError: name 'sns' is not defined
在探索式数据分析⼯作中,同时观察⼀组变量的散布图是很有意
# 义的,这也被称为散布图矩阵(scatter plot matrix)。纯⼿⼯创
# 建这样的图表很费⼯夫,所以seaborn提供了⼀个便捷的pairplot
# 函数,它⽀持在对⻆线上放置每个变量的直⽅图或密度估计
# 在探索式数据分析⼯作中,同时观察⼀组变量的散布图是很有意
# 义的,这也被称为散布图矩阵(scatter plot matrix)。纯⼿⼯创
# 建这样的图表很费⼯夫,所以seaborn提供了⼀个便捷的pairplot
# 函数,它⽀持在对⻆线上放置每个变量的直⽅图或密度估计
sns.pairplot(trans_data, diag_kind='kde', plot_kws={'alpha': 0.2})
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-78-600bfa6b3884> in <module>()
      3 # 建这样的图表很费⼯夫,所以seaborn提供了⼀个便捷的pairplot
      4 # 函数,它⽀持在对⻆线上放置每个变量的直⽅图或密度估计
----> 5 sns.pairplot(trans_data, diag_kind='kde', plot_kws={'alpha': 0.2})

NameError: name 'sns' is not defined
Facet Grids and Categorical Data
分⾯⽹格(facet grid)和类型数据
# 要是数据集有额外的分组维度呢?有多个分类变量的数据可视化
# 的⼀种⽅法是使⽤⼩⾯⽹格。seaborn有⼀个有⽤的内置函数
# factorplot,可以简化制作多种分⾯图
# 分⾯⽹格(facet grid)和类型数据
# 要是数据集有额外的分组维度呢?有多个分类变量的数据可视化
# 的⼀种⽅法是使⽤⼩⾯⽹格。seaborn有⼀个有⽤的内置函数
# factorplot,可以简化制作多种分⾯图
sns.factorplot(x='day', y='tip_pct', hue='time', col='smoker',
               kind='bar', data=tips[tips.tip_pct < 1])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-80-85f85dfbf016> in <module>()
      3 # 的⼀种⽅法是使⽤⼩⾯⽹格。seaborn有⼀个有⽤的内置函数
      4 # factorplot,可以简化制作多种分⾯图
----> 5 sns.factorplot(x='day', y='tip_pct', hue='time', col='smoker',
      6                kind='bar', data=tips[tips.tip_pct < 1])

NameError: name 'sns' is not defined
sns.factorplot(x='day', y='tip_pct', row='time',
               col='smoker',
               kind='bar', data=tips[tips.tip_pct < 1])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-81-ae195753dd06> in <module>()
----> 1 sns.factorplot(x='day', y='tip_pct', row='time',
      2                col='smoker',
      3                kind='bar', data=tips[tips.tip_pct < 1])

NameError: name 'sns' is not defined
factorplot⽀持其它的绘图类型,你可能会⽤到。例如,盒图(它
# 可以显示中位数,四分位数,和异常值)就是⼀个有⽤的可视化
# factorplot⽀持其它的绘图类型,你可能会⽤到。例如,盒图(它
# 可以显示中位数,四分位数,和异常值)就是⼀个有⽤的可视化
sns.factorplot(x='tip_pct', y='day', kind='box',
               data=tips[tips.tip_pct < 0.5])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-83-738b9adde090> in <module>()
      1 # factorplot⽀持其它的绘图类型,你可能会⽤到。例如,盒图(它
      2 # 可以显示中位数,四分位数,和异常值)就是⼀个有⽤的可视化
----> 3 sns.factorplot(x='tip_pct', y='day', kind='box',
      4                data=tips[tips.tip_pct < 0.5])

NameError: name 'sns' is not defined
Other Python Visualization Tools
pd.options.display.max_rows = PREVIOUS_MAX_ROWS

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值