目录
任务简介:
前面已经学习了强大的数据处理工具pandas,现在想把原始数据及处理结果通过图像的方式展示出来,强大的可视化工具matplotlib库可担此重任。
任务说明:
-
掌握matplotlib绘图风格的设置。
-
掌握matplotlib二维折线图、散点图、直方图、多子图等基本图像的绘制及线宽、颜色、标记、标签、刻度、图例、标题等元素的修饰方法。
-
了解matpotlib三维图像的绘制。
-
了解基于matplotlib的高级版本seabon库。
-
了解Pandas类型数据绘制图形的直接方法。
一、环境配置
1. 要不要plt.show()
-
ipython中可用魔术方法 %matplotlib inline
-
pycharm 中必须使用plt.show()
导包:
%matplotlib inline
import matplotlib.pyplot as plt
若要设定全局样式,则导包后添加:
plt.style.use("seaborn-whitegrid") # " "内可以换成其它的样式
输入:
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
plt.ylabel("squares")
输出:
2. 设置样式
查看前五个样式:
plt.style.available[:5]
输出:
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background']
输入:
with plt.style.context("seaborn-white"):
plt.plot(x, y)
输出:
3. 解决Matplotlib无法输出中文的问题
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei'] # 指定默认字体为微软雅黑
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
正确输出了中文:
4. 将图像保存为文件
输入:
import numpy as np
x = np.linspace(0, 10 ,100) # 均匀生成[0,10]之间的数100个
plt.plot(x, np.exp(x))
plt.savefig("my_figure.png")
输出:
二、Matplotlib库
1. 折线图
导包:
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
import numpy as np
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
输出:
- 绘制多条曲线
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.cos(x))
plt.plot(x, np.sin(x))
输出:
1.1 调整线条颜色和风格
- 调整线条颜色
输入:
offsets = np.linspace(0, np.pi, 5)
colors = ["blue", "g", "r", "yellow", "pink"]
for offset, color in zip(offsets, colors):
plt.plot(x, np.sin(x-offset), color=color) # color可缩写为c
输出:
- 调整线条风格
输入:
x = np.linspace(0, 10, 11)
offsets = list(range(8))
linestyles = ["solid", "dashed", "dashdot", "dotted", "-", "--", "-.", ":"] #"-", "--", "-.", ":" 分别表示:"solid", "dashed", "dashdot", "dotted"
for offset, linestyle in zip(offsets, linestyles):
plt.plot(x, x+offset, linestyle=linestyle) # linestyle可简写为ls
输出:
- 调整线宽
输入:
x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
linewidths = (i*2 for i in range(1,5))
for offset, linewidth in zip(offsets, linewidths):
plt.plot(x, x+offset, linewidth=linewidth) # linewidth可简写为lw
输出:
- 调整数据点标记
输入:
x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
markers = ["*", "+", "o", "s"]
for offset, marker in zip(offsets, markers):
plt.plot(x, x+offset, marker=marker)
输出:
输入:
x = np.linspace(0, 10, 11)
offsets = list(range(0, 12, 3))
markers = ["*", "+", "o", "s"]
for offset, marker in zip(offsets, markers):
plt.plot(x, x+offset, marker=marker, markersize=10) # markersize可简写为ms
输出:
- 颜色跟风格设置的简写
输入:
x = np.linspace(0, 10, 11)
offsets = list(range(0, 8, 2))
color_linestyles = ["g-", "b--", "k-.", "r:"]
for offset, color_linestyle in zip(offsets, color_linestyles):
plt.plot(x, x+offset, color_linestyle)
输出:
输入:
x = np.linspace(0, 10, 11)
offsets = list(range(0, 8, 2))
color_marker_linestyles = ["g*-", "b+--", "ko-.", "rs:"]
for offset, color_marker_linestyle in zip(offsets, color_marker_linestyles):
plt.plot(x, x+offset, color_marker_linestyle)
输出:
其他用法及颜色缩写、数据点标记缩写等可点击查看官方文档
1.2 调整坐标轴
- xlim, ylim
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.xlim(-1, 7)
plt.ylim(-1.5, 1.5)
输出:
- axis
将x和y的范围一起设定
plt.axis([x1, x2, y1, y2]) # [xmin, xmax, ymin, ymax]
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis([-2, 8, -2, 2])
输出:
使图像紧凑
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis("tight")
输出:
使图像扁平
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.axis("equal")
输出:
查看plt.axis
帮助
输入:
?plt.axis
输出:
Signature: plt.axis(*args, emit=True, **kwargs)
Docstring:
Convenience method to get or set some axis properties.
Call signatures::
xmin, xmax, ymin, ymax = axis()
xmin, xmax, ymin, ymax = axis([xmin, xmax, ymin, ymax])
xmin, xmax, ymin, ymax = axis(option)
xmin, xmax, ymin, ymax = axis(**kwargs)
Parameters
----------
xmin, xmax, ymin, ymax : float, optional
The axis limits to be set. This can also be achieved using ::
ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))
option : bool or str
If a bool, turns axis lines and labels on or off. If a string,
possible values are:
======== ==========================================================
Value Description
======== ==========================================================
'on' Turn on axis lines and labels. Same as ``True``.
'off' Turn off axis lines and labels. Same as ``False``.
'equal' Set equal scaling (i.e., make circles circular) by
changing axis limits. This is the same as
``ax.set_aspect('equal', adjustable='datalim')``.
Explicit data limits may not be respected in this case.
'scaled' Set equal scaling (i.e., make circles circular) by
changing dimensions of the plot box. This is the same as
``ax.set_aspect('equal', adjustable='box', anchor='C')``.
Additionally, further autoscaling will be disabled.
'tight' Set limits just large enough to show all data, then
disable further autoscaling.
'auto' Automatic scaling (fill plot box with data).
'image' 'scaled' with axis limits equal to data limits.
'square' Square plot; similar to 'scaled', but initially forcing
``xmax-xmin == ymax-ymin``.
======== ==========================================================
emit : bool, default: True
Whether observers are notified of the axis limit change.
This option is passed on to `~.Axes.set_xlim` and
`~.Axes.set_ylim`.
Returns
-------
xmin, xmax, ymin, ymax : float
The axis limits.
See Also
--------
matplotlib.axes.Axes.set_xlim
matplotlib.axes.Axes.set_ylim
File: d:\anaconda3\lib\site-packages\matplotlib\pyplot.py
Type: function
- 对数坐标
输入:
x = np.logspace(0, 5, 100)
plt.plot(x, np.log(x))
plt.xscale("log")
输出:
- 调整坐标轴刻度
输入:
x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.xticks(np.arange(0, 12, step=1))
输出:
输入:
x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.xticks(np.arange(0, 12, step=1), fontsize=15)
plt.yticks(np.arange(0, 110, step=10))
输出:
- 调整刻度样式
输入:
x = np.linspace(0, 10, 100)
plt.plot(x, x**2)
plt.tick_params(axis="both", labelsize=15)
输出:
1.3 设置图形标签
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
plt.title("A Sine Curve", fontsize=20)
plt.xlabel("x", fontsize=15)
plt.ylabel("sin(x)", fontsize=15)
输出:
1.4 设置图例
- 默认
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-", label="Sin")
plt.plot(x, np.cos(x), "r--", label="Cos")
plt.legend()
输出:
- 修饰图例
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-", label="Sin")
plt.plot(x, np.cos(x), "r--", label="Cos")
plt.ylim(-1.5, 2)
plt.legend(loc="upper center", frameon=True, fontsize=15) # frameon=True,图例增加外框
输出:
1.5 添加文字和箭头
- 添加文字
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-")
plt.text(3.5, 0.5, "y=sin(x)", fontsize=15) # 3.5,0.5为文字的坐标
输出:
- 添加箭头
输入:
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x), "b-")
plt.annotate('local min', xy=(1.5*np.pi, -1), xytext=(4.5, 0),
arrowprops=dict(facecolor='black', shrink=0.1),
)
输出:
2. 散点图
2.1 简单散点图
输入:
x = np.linspace(0, 2*np.pi, 20)
plt.scatter(x, np.sin(x), marker="o", s=30, c="r") # s 大小 c 颜色
输出:
2.3 颜色配置
输入:
x = np.linspace(0, 10, 100)
y = x**2
plt.scatter(x, y, c=y, cmap="inferno")
plt.colorbar()
输出:
颜色配置可点击参考官方文档
2.4 根据数据控制点的大小
输入:
x, y, colors, size = (np.random.rand(100) for i in range(4))
plt.scatter(x, y, c=colors, s=1000*size, cmap="viridis")
输出:
2.5 透明度
在2.4基础上增加了参数alpha
输入:
x, y, colors, size = (np.random.rand(100) for i in range(4))
plt.scatter(x, y, c=colors, s=1000*size, cmap="viridis", alpha=0.3)
plt.colorbar()
输出:
2.6 随机漫步
输入:
from random import choice
class RandomWalk():
"""一个生产随机漫步的类"""
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
if x_step == 0 or y_step == 0:
continue
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
rw = RandomWalk(10000)
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.figure(figsize=(12, 6))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap="inferno", s=1)
plt.colorbar()
plt.scatter(0, 0, c="green", s=100) # 起始点
plt.scatter(rw.x_values[-1], rw.y_values[-1], c="red", s=100) # 终点
plt.xticks([]) # 隐藏坐标轴
plt.yticks([])
输出:
3. 柱形图
3.1 简单柱形图
输入:
x = np.arange(1, 6)
plt.bar(x, 2*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
plt.tick_params(axis="both", labelsize=13)
输出:
输入:
x = np.arange(1, 6)
plt.bar(x, 2*x, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
plt.xticks(x, ('G1', 'G2', 'G3', 'G4', 'G5')) # 前面为原先的值,后面为替换的值
plt.tick_params(axis="both", labelsize=13)
输出:
下面的方法和上面效果一样
输入:
x = ('G1', 'G2', 'G3', 'G4', 'G5')
y = 2 * np.arange(1, 6)
plt.bar(x, y, align="center", width=0.5, alpha=0.5, color='yellow', edgecolor='red')
plt.tick_params(axis="both", labelsize=13)
输出:
输入:
x = ["G"+str(i) for i in range(5)]
y = 1/(1+np.exp(-np.arange(5)))
colors = ['red', 'yellow', 'blue', 'green', 'gray']
plt.bar(x, y, align="center", width=0.5, alpha=0.5, color=colors)
plt.tick_params(axis="both", labelsize=13)
输出:
3.2 累加柱形图
输入:
x = np.arange(5)
y1 = np.random.randint(20, 30, size=5)
y2 = np.random.randint(20, 30, size=5)
plt.bar(x, y1, width=0.5, label="man")
plt.bar(x, y2, width=0.5, bottom=y1, label="women")
plt.legend()
输出:
3.3 并列柱形图
输入:
x = np.arange(15)
y1 = x+1
y2 = y1+np.random.random(15)
plt.bar(x, y1, width=0.3, label="man")
plt.bar(x+0.3, y2, width=0.3, label="women")
plt.legend()
输出:
3.4 横向柱形图
输入:
x = ['G1', 'G2', 'G3', 'G4', 'G5']
y = 2 * np.arange(1, 6)
plt.barh(x, y, align="center", height=0.5, alpha=0.8, color="blue", edgecolor="red") # bar改成barh就是横向图
plt.tick_params(axis="both", labelsize=13)
输出:
4. 多子图
4.1 简单多子图
输入:
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.subplot(211)
plt.plot(t1, f(t1), "bo-", markerfacecolor="r", markersize=5) # 211前两个数字代表创建2行1列的多子图,第三个数字表示改图为第1个
plt.title("A tale of 2 subplots")
plt.ylabel("Damped oscillation")
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), "r--")
plt.xlabel("time (s)")
plt.ylabel("Undamped")
输出:
4.2 多行多列子图
输入:
x = np.random.random(10)
y = np.random.random(10)
plt.subplots_adjust(hspace=0.5, wspace=0.3)
plt.subplot(321)
plt.scatter(x, y, s=80, c="b", marker=">")
plt.subplot(322)
plt.scatter(x, y, s=80, c="g", marker="*")
plt.subplot(323)
plt.scatter(x, y, s=80, c="r", marker="s")
plt.subplot(324)
plt.scatter(x, y, s=80, c="c", marker="p")
plt.subplot(325)
plt.scatter(x, y, s=80, c="m", marker="+")
plt.subplot(326)
plt.scatter(x, y, s=80, c="y", marker="H")
输出:
4.3 不规则多子图
输入:
def f(x):
return np.exp(-x) * np.cos(2*np.pi*x)
x = np.arange(0.0, 3.0, 0.01)
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3) # 先画一个2*3的网格
plt.subplot(grid[0, 0]) # 第0行第0列
plt.plot(x, f(x))
plt.subplot(grid[0, 1:]) # 第0行第1列及以后的列
plt.plot(x, f(x), "r--", lw=2)
plt.subplot(grid[1, :]) # 第1行所有列
plt.plot(x, f(x), "g-.", lw=3)
输出:
5.直方图
5.1 普通频次直方图
输入:
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000) # np.random.randn 生成的为标准正态分布数据
plt.hist(x, bins=50, facecolor='g', alpha=0.75) # bins:矩形条个数
输出:
5.2 概率密度
输入:
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
plt.hist(x, 50, density=True, color="r") # 加density=True显示概率密度图
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
输出:
显示空心图
输入:
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
plt.hist(x, bins=50, density=True, color="r", histtype='step') # histtype='step' 显示空心图
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
输出:
输入:
from scipy.stats import norm
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
_, bins, __ = plt.hist(x, 50, density=True)
y = norm.pdf(bins, mu, sigma) # 计算bins中的点对应的正态分布的数值
plt.plot(bins, y, 'r--', lw=3)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.xlim(40, 160)
plt.ylim(0, 0.03)
输出:
5.3 累计概率分布
输入:
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
plt.hist(x, 50, density=True, cumulative=True, color="r")
plt.xlabel('Smarts')
plt.ylabel('Cum_Probability')
plt.title('Histogram of IQ')
plt.text(60, 0.8, r'$\mu=100,\ \sigma=15$')
plt.xlim(50, 165)
plt.ylim(0, 1.1)
输出:
【例】模拟投两个骰子
模拟一个骰子:
class Die():
"模拟一个骰子的类"
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
return np.random.randint(1, self.num_sides+1)
- 重复投一个骰子
输入:
die = Die()
results = []
for i in range(60000):
result = die.roll()
results.append(result)
plt.hist(results, bins=6, range=(0.75, 6.75), align="mid", width=0.5)
plt.xlim(0 ,7)
输出:
- 重复投两个骰子
输入:
die1 = Die()
die2 = Die()
results = []
for i in range(60000):
result = die1.roll()+die2.roll()
results.append(result)
plt.hist(results, bins=11, range=(1.75, 12.75), align="mid", width=0.5)
plt.xlim(1 ,13)
plt.xticks(np.arange(1, 14))
输出:
6. 误差图
6.1 基本误差图
输入:
x = np.linspace(0, 10 ,50)
dy = 0.5
y = np.sin(x) + dy*np.random.randn(50)
plt.errorbar(x, y , yerr=dy, fmt="+")
输出:
6.2 柱形图误差图
输入:
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = ['G1', 'G2', 'G3', 'G4', 'G5']
width = 0.35
p1 = plt.bar(ind, menMeans, width=width, label="Men", yerr=menStd)
p2 = plt.bar(ind, womenMeans, width=width, bottom=menMeans, label="Men", yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.yticks(np.arange(0, 81, 10))
plt.legend()
输出:
7. 面向对象的风格简介
7.1 普通图
add_axes()
方法需要一个由4个元素组成的list对象,分别对应图形的左、底、宽、高。每个数字必须在0和1之间。
输入:
x = np.linspace(0, 5, 10)
y = x ** 2
fig = plt.figure(figsize=(8,4), dpi=80) # 图像
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # 轴 left, bottom, width, height (range 0 to 1)
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
输出:
7.2 画中画
输入:
x = np.linspace(0, 5, 10)
y = x ** 2
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax2 = fig.add_axes([0.2, 0.5, 0.4, 0.3])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
ax2.plot(y, x, 'g')
ax2.set_xlabel('y')
ax2.set_ylabel('x')
ax2.set_title('insert title')
输出:
7.3 多子图
输入:
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 3.0, 0.01)
fig= plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
ax1 = plt.subplot(2, 2, 1)
ax1.plot(t1, f(t1))
ax1.set_title("Upper left")
ax2 = plt.subplot(2, 2, 2)
ax2.plot(t1, f(t1))
ax2.set_title("Upper right")
ax3 = plt.subplot(2, 1, 2)
ax3.plot(t1, f(t1))
ax3.set_title("Lower")
输出:
8. 三维图形简介
8.1 三维数据点与线
输入:
from mpl_toolkits import mplot3d
ax = plt.axes(projection="3d")
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline ,zline)
zdata = 15*np.random.random(100)
xdata = np.sin(zdata)
ydata = np.cos(zdata)
ax.scatter3D(xdata, ydata ,zdata, c=zdata, cmap="spring")
输出:
8.2 三维数据曲面图
输入:
def f(x, y):
return np.sin(np.sqrt(x**2 + y**2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, cmap="viridis")
输出:
输入:
t = np.linspace(0, 2*np.pi, 1000)
X = np.sin(t)
Y = np.cos(t)
Z = np.arange(t.size)[:, np.newaxis]
ax = plt.axes(projection="3d")
ax.plot_surface(X, Y, Z, cmap="viridis")
输出:
9. 等高线图在梯度下降中的应用
等高线图常用于深度学习中绘制梯度下降的效果图,对研究比较有意义。
下面以一个例子说明梯度下降的问题:
【举个栗子】求解损失函数 f ( x ) = 0.1 x 1 2 + 2 x 2 2 f(x)= 0.1x_1^2+2x_2^2 f(x)=0.1x12+2x22的最小值
9.1 绘制函数三维图像
定义 x 1 , x 2 x_1,x_2 x1,x2:
x1, x2 = np.meshgrid(np.arange(-5.5, 1.0, 0.1), np.arange(-3.0, 1.0, 0.1)) # np.meshgrid()常用于生成网格图、三维图的x,y
绘制三维图像:
ax = plt.axes(projection="3d")
ax.plot_surface(x1, x2 ,f_2d(x1, x2), cmap="viridis")
输出:
9.2 绘制等高线和梯度下降曲线
定义相关函数:
eta = 0.4 # 学习率
# 计算函数值
def f_2d(x1, x2):
return 0.1 * x1 ** 2 + 2 * x2 ** 2
# 梯度下降更新x1,x2
def gd_2d(x1, x2):
return (x1 - eta * 0.2 * x1, x2 - eta * 4 * x2)
# 使用给定的自变量更新函数
def train_2d(trainer):
x1, x2 = -5, -2
results = [(x1, x2)]
for i in range(20):
x1, x2 = trainer(x1, x2)
results.append((x1, x2))
print('epoch %d, x1 %f, x2 %f' % (i + 1, x1, x2))
return results
绘制等高线和梯度下降曲线:
plt.contour(x1,x2,f_2d(x1, x2),colors='g') # 画等高线
plt.plot(*zip(*train_2d(gd_2d)),'o-',c='orange') # 画优化路线,*zip(*n):zip(*n)解压n,*zip(*n)将解压的数据映射成(x,y)的形式,便于画图
plt.xlabel('x1')
plt.ylabel('x2')
输出:
epoch 20, x1 -0.943467, x2 -0.000073
三、Seaborn库-文艺青年的最爱
1. Seaborn 与 Matplotlib
Seaborn 是一个基于 matplotlib 且数据结构与 pandas 统一的统计图制作库
Matplotlib效果:
输入:
x = np.linspace(0, 10, 500)
y = np.cumsum(np.random.randn(500, 6), axis=0)
with plt.style.context("classic"):
plt.plot(x, y)
plt.legend("ABCDEF", ncol=2, loc="upper left")
输出:
seaborn 效果:
输入:
import seaborn as sns
x = np.linspace(0, 10, 500)
y = np.cumsum(np.random.randn(500, 6), axis=0)
sns.set()
plt.figure(figsize=(10, 6))
plt.plot(x, y)
plt.legend("ABCDEF", ncol=2, loc="upper left")
输出:
2. 柱形图的对比
Matplotlib效果:
输入:
x = ['G1', 'G2', 'G3', 'G4', 'G5']
y = 2 * np.arange(1, 6)
plt.figure(figsize=(8, 4))
plt.barh(x, y, align="center", height=0.5, alpha=0.8, color="blue")
plt.tick_params(axis="both", labelsize=13)
输出:
输入:
plt.figure(figsize=(8, 4))
x = ['G5', 'G4', 'G3', 'G2', 'G1']
y = 2 * np.arange(5, 0, -1)
# sns.barplot(y, x)
sns.barplot(y, x, linewidth=5)
输出:
查看seaborn barplot官方文档
输入:
sns.barplot?
3. 鸢尾花数据集案例
输入:
iris = sns.load_dataset("iris")
iris.head()
输出:
查看鸢尾花数据集中四个特征之间的相互关系:
输入:
sns.pairplot(data=iris, hue="species")
输出:
四、Pandas 中的绘图函数概览
1. 线形图
输入:
import pandas as pd
df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
columns=list("ABCD"),
index=np.arange(1000))
df.head()
输出:
输入:
df.plot()
输出:
2. 柱形图
输入:
df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2
输出:
2.1 多组数据竖图
输入:
df2.plot.bar()
输出:
2.2 多组数据累加竖图
输入:
df2.plot.bar(stacked=True)
输出:
2.3 多组数据累加横图
输入:
df2.plot.barh(stacked=True)
输出:
3. 直方图和密度图
输入:
df4 = pd.DataFrame({"A": np.random.randn(1000) - 3, "B": np.random.randn(1000),
"C": np.random.randn(1000) + 3})
df4.head()
输出:
3.1 普通直方图
输入:
df4.plot.hist(bins=50)
输出:
3.2 累加直方图
输入:
df4['A'].plot.hist(cumulative=True)
输出:
3.3 概率密度图
输入:
df4['A'].plot(kind="kde")
输出:
3.4 差分
输入:
df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
columns=list("ABCD"),
index=np.arange(1000))
df.head()
输出:
输入:
df.diff().hist(bins=50, color="r")
输出:
4. 散点图
输入:
housing = pd.read_csv("housing.csv")
housing.head()
输出:
输入:
"""基于地理数据的人口、房价可视化"""
# 圆的半价大小代表每个区域人口数量(s),颜色代表价格(c),用预定义的jet表进行可视化
with sns.axes_style("white"):
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.6,
s=housing["population"]/100, label="population",
c="median_house_value", cmap="jet", colorbar=True, figsize=(12, 8))
plt.legend()
plt.axis([-125, -113.5, 32, 43])
输出:
输入:
housing.plot(kind="scatter", x="median_income", y="median_house_value", alpha=0.8)
输出:
5. 多子图
输入:
df = pd.DataFrame(np.random.randn(1000, 4).cumsum(axis=0),
columns=list("ABCD"),
index=np.arange(1000))
df.head()
输出:
- 默认情形
输入:
df.plot(subplots=True, figsize=(6, 16))
输出:
- 设定图形安排
输入:
df.plot(subplots=True, layout=(2, 2), figsize=(16, 6), sharex=False)
输出: