13. 日月光华 Python数据分析-Pandas-绘图

# matplotlib是python中的一个绘图库,功能非常强大,但是它是一种相对低级的绘图工具,画一个图要用到很多基础组件,写很多代码。在pandas中,我们有行标签、列标签以及分组数据,也就是说制作一张图表的很多基础信息pandas中就自然包括了,所以说,pandas能用一两条语句,很简洁的来创建绘图。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline
import matplotlib
plt.style.use("ggplot")   # 选择matplotlib的样式

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))     # 1000个随机数,默认index是x轴,数据y轴
ts = ts.cumsum()
ts.plot(title='sum')
plt.xlabel('time')
plt.ylabel('cum')
image.png
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))     #你也可以同时画很多列,使用DataFrame
df = df.cumsum()
df.plot()
image.png
df['E'] = np.arange(1000)    # 添加一列E
df.plot(x='E', y='A')              # 指定E作为x轴,A为y轴
image.png
# ‘bar’ 或 ‘barh’ 柱状图
# ‘hist’ 直方图
# ‘box’ 盒子图
# ‘kde’ or 'density' 密度图
# ‘area’ 面积图
# ‘scatter’ for 散点图
# ‘pie’ 饼图

df.iloc[5]    # 取出第5天的数据
# A    0.931832
# B    2.641881
# C    4.161359
# D   -1.873559
# E    5.000000
# Name: 2000-01-06 00:00:00, dtype: float64

# df.iloc[5].plot.bar()   # 绘制柱状图
df.iloc[5].plot.barh()    # 绘制横向柱状图
plt.axvline(0, color='r')  # 绘制垂直方向的竖线,在坐标为0的位置
image.png
df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2.plot.barh(stacked=True)    # 水平堆积柱状体
image.png
df4 = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000), 'c': np.random.randn(1000) - 1}, columns=['a', 'b', 'c'])                   #数据的分布情况
df4.plot.hist(bins=50)
image.png
df4.plot.hist(bins=50, subplots=True)
image.png
df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])    #必须全为正数或者负数
df.plot.area()
image.png
df = pd.DataFrame(np.random.rand(50, 4), columns=['a', 'b', 'c', 'd'])
ax = df.plot.scatter(x='a', y='b', label='comp1')
df.plot.scatter(x='c', y='d', color='r', ax=ax, label='comp2')
image.png
df.plot.scatter(x='a', y='b', s=df.c*200)   # s参数用于指定点的面积大小
image.png
series = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
series.plot.pie(figsize=(5,5))
image.png
df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])  
df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000), columns=list('ABCD'))
df = df.cumsum()

你可能感兴趣的:(13. 日月光华 Python数据分析-Pandas-绘图)