文章目录
绘制子图(01 02 经常使用)
01 创建画布 matplotlib.pyplot.figure()
用于画一张图 或者 创建画布,再添加子图
matplotlib.pyplot.figure(num=None, figsize=None)
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,20,1) # arange([start,] stop[, step,])
y = np.random.rand(20)
y = y.cumsum()
plt.figure()
plt.scatter(x,y,label='hehe')
plt.grid(linestyle='--')
plt.legend()
plt.show()
02 创建一个画布和一组子图matplotlib.pyplot.subplots(nrows=1, ncols=1)
nrows, ncols : int, optional, default: 1 子图网络的行列数.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.random.rand(20)
y1 = np.random.rand(20)
y1= y1.cumsum()
y2 = np.sin(x)
y2= y2.cumsum()
data = pd.DataFrame({"a":y1,"b":y2})
print(data.head())
fig, axes = plt.subplots(1,3,figsize=(10,4)) # 创建一个画布和一组子图
data.plot(ax=axes[0])#添加第一个子图
axes[1].scatter(data.index,data["a"])# 添加第二个子图 两个方式都可以
axes[2].plot(data.index,data["a"])
plt.show()
03 当前图中加子图matplotlib.pyplot.subplot(*args, **kwargs)
一个子图一个子图的画
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(101)
x = np.random.rand(20)
y1 = np.random.rand(20)
y2 = y1*100
fig = plt.figure(figsize=(10,5)) # 画一个画布 大小(10,5) 没有此句不影响画图,但没有大小限制
plt.subplot(121)# 添加1行2列 位置1子图
plt.scatter(x,y1)# 就近子图画图
plt.subplot(122)
plt.scatter(x,y2)
plt.show()
04 向图中加入子图的轴 fig.add_subplot(*args, **kwargs)
module ‘matplotlib.pyplot’ has no attribute ‘add_subplot’
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.random.rand(20)
y1 = np.random.rand(20)
y2 = np.sin(x)
fig = plt.figure(figsize=(10,4)) # 创建一个画布
fig.add_subplot(121) # 添加子图
plt.scatter(x,y1)
fig.add_subplot(122)# 添加子图
plt.scatter(x,y2)
plt.show()
基本图表绘制 plt.plot()
绘图方法主要有两种
01 plt.plot(x,y,kind=‘line’)
02 ts.plot(kind=‘line’)
当画简单图时, 建议使用ts.plot() 在这里ts可以代表Series 和 DataFrame.
今天这里主要讲 ts.plot()
首先说到图表类别(kind), 主要有以下几种:
线形图、柱状图、密度图,以横纵坐标两个维度为主
同时可延展出多种其他图表样式
ts.plot(这里参数较多, 但常用的只有那么几个, 默认是线形图, 可更改)
Series.plot()
ts.plot(kind='line', ax=None, figsize=None, use_index=True, title=None,
grid=None, legend=False, style=None, logx=False, logy=False, loglog=False,
xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None,
colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, **kwds)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# % matplotlib notebook
% matplotlib inline
# 1 Series 直接生成图表
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum() # 通常用于计算一个数组各行的累加值
df = pd.DataFrame({
"a":np.random.randn(1000),
"b":np.random.randn(1000)
},index=pd.date_range('1/1/2000', periods=1000))
df= df.cumsum()
# 1 教学用例
ts.plot(kind='line', label='hehe', style="--g.", color="red", alpha=0.4, grid=True,
use_index = True, rot = 45, ylim=[-30,60], figsize=(12,4), title='test', legend=True)
# 2 实践中使用较多
ts.plot(kind='line', label='hehe', style="--g.", color="red", alpha=0.4,
use_index = True, rot = 45, ylim=[-30,60], figsize=(12,4), title='test')
plt.grid(linestyle="--") # 显示网格
plt.legend() #显示标签
- kind 图表类型, line,bar,barh…(折线图,柱状图,柱状图-横…)
- label 标签名, Dataframe格式以列名为label
- style 线的格式
- color 颜色
- alpha 透明度, 0-1
- grid 网格线 一般直接画网格,不在这里列为参数, plt.grid() --> plt.grid(True, linestyle = “–”,color = “gray”, linewidth = “0.5”,axis = ‘x’)
- use_index = True 代表使用index作为横坐标, 否则默认1-n. 默认为True
- rot 旋转刻度标签,0-360
- xlim, ylim 横轴 纵轴的范围
- figsize 图的大小
- title 图表的题目
- legend = False不显示图中的标签(标签名label ) , 默认False, 如果要显示的话, legend = True, 一般直接用plt.legend()
DataFrame.plot()
以上是Series直接作图的示例, 那么DataFrame直接生成图表应该怎么做呢? 基本一致,仅仅是某些参数的不同.
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(kind='line',
style = '--.',
alpha = 0.4,
use_index = True,
rot = 45,
figsize = (8,4),
title = 'test',
subplots = False,
colormap = 'RdYlBu_r')
plt.grid(linestyle="--")
plt.legend()
- subplots=True 可以直接创建子图, 默认False 在一张图中显示
- colormap 是颜色图,可以自动填充多种颜色
修改subplots = True 后
柱状图
01 plt.plot(x, y, kind=‘bar’) , plt.bar(x, y) 这两个是相同效果, 后者是简写
这两个一样,内部参数也一致. 注意没有plt.line() 因为plot()中kind的默认参数是line, 因此用plt.plot() 代替.
02 Series.plot(kind=‘bar’) , Series.plot.bar() 这两个是相同效果, 后者是最新版支持的写法
简单的图建议, DataFrame 同样适用.
fig, axes = plt.subplots(4,1,figsize=(16,16))
plt.grid(linestyle='--')
s = pd.Series(np.random.randint(0,10,16),index = list('abcdefghijklmnop'))
df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])
s.plot(kind='bar', ax=axes[0], color='g', edgecolor='black')
df.plot(kind='bar', ax=axes[1], colormap='Reds_r', edgecolor='black')
df.plot(kind='bar', ax=axes[2], stacked=True, colormap='Blues_r', edgecolor='black')
df.plot(kind='barh', ax=axes[3], edgecolor='black')