Matplotlib Bokeh Seaborn
Matplotlib Bokeh Seaborn
fig, ax = [Link]()
[Link](X, Y, Y∕4)
1 [Link](Y2, X, color=”C0”)
21
1.0 [Link](None)
0.5 Tweak ax.set_title(”A Sine wave”)
1234567
0.0
0.5 You can modify pretty much anything in a plot, including lim-
[Link](X, Y)
1.0 its, colors, markers, line width and styles, ticks and ticks la-
0 5 10 15 20 25 30 ax.set_ylabel(None)
bels, titles, etc.
ax.set_xlabel(”Time”)
765
Time
Choose X = [Link](0, 10, 100)
Y = [Link](X) 432 Explore
Matplotlib offers several kind of plots (see Gallery): [Link](X, Y, color=”black”)
1 Figures are shown with a graphical user interface that al-
X = [Link](0, 1, 100) 765 X = [Link](0, 10, 100) 765 1234567 lows to zoom and pan the figure, to navigate between the
Y = [Link](0, 1, 100) 432 Y = [Link](X) 432 different views and to show the value under the mouse.
[Link](X, Y)
1 [Link](X, Y, linestyle=”--”)
1
X = [Link](10) 765 1234567 X = [Link](0, 10, 100) 765 1234567 Save (bitmap or vector format)
Y = [Link](1, 10, 10) 432 Y = [Link](X) 432
[Link](X, Y)
1 [Link](X, Y, linewidth=5)
1 [Link](”[Link]”, dpi=300)
[Link](”[Link]”)
Z = [Link](0, 1, (8,8)) 765 1234567 X = [Link](0, 10, 100) 765 1234567
432 Y = [Link](X) 432
1 1
Matplotlib 3.5.0 handout for beginners. Copyright (c) 2021 Matplotlib Development
[Link](Z) [Link](X, Y, marker=”o”) Team. Released under a CC-BY 4.0 International License. Supported by NumFOCUS.
1234567 1234567
Matplotlib for intermediate users
A matplotlib figure is composed of a hierarchy of elements Ticks & labels Legend
that forms the actual figure. Each element can be modified.
from [Link] import MultipleLocator as ML [Link](X, [Link](X), ”C0”, label=”Sine”)
from [Link] import ScalarFormatter as SF [Link](X, [Link](X), ”C1”, label=”Cosine”)
4
Anatomy of a figure [Link].set_minor_locator(ML(0.2)) [Link](bbox_to_anchor=(0,1,1,.1),ncol=2,
Title Blue signal [Link].set_minor_formatter(SF()) mode=”expand”, loc=”lower left”)
Major tick Red signal ax.tick_params(axis=’x’,which=’minor’,rotation=90)
Legend Sine Sine and Cosine Cosine
Minor tick 0 1 2 3 4 5
0.2
0.4
0.6
0.8
1.2
1.4
1.6
1.8
2.2
2.4
2.6
2.8
3.2
3.4
3.6
3.8
4.2
4.4
4.6
4.8
3
Major tick label Grid Lines & markers
Line
(line plot)
X = [Link](0.1, 10*[Link], 1000) Annotation
Y axis label
2 Y = [Link](X)
[Link](X, Y, ”C1o:”, markevery=25, mec=”1.0”) [Link](”A”, (X[250],Y[250]),(X[250],-1),
Y axis label Markers ha=”center”, va=”center”,arrowprops =
(scatter plot) 1 {”arrowstyle” : ”->”, ”color”: ”C1”})
0
1 1 1
0 5 10 15 20 25 30 0
Spines 1 A
Figure Line 0 5 10 15 20 25 30
Axes (line plot) Scales & projections
0
0 0.25 0.50 0.75 1 1.25 1.50 1.75 2 2.25 2.50 2.75 3 3.25 3.50 3.75 4 Colors
X axis label fig, ax = [Link]()
Minor tick label
X axis label ax.set_xscale(”log”)
[Link](X, Y, ”C1o-”, markevery=25, mec=”1.0”) 1 AnyC0
color can be used, but Matplotlib offers sets of colors:
C1 C2 C3 C4 C5 C6 C7 C8 C9
10 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
Figure, axes & spines
1 0 2 4 6 8 10 12 14 16
0 0
1 0 2 4 6 8 10 12 14 16
fig, axs = [Link](3,3) 10 1 100 101
Size & DPI
axs[0,0].set_facecolor(”#ddddff”)
axs[2,2].set_facecolor(”#ffffdd”) Text & ornaments Consider a square figure to be included in a two-columns A4
paper with 2cm margins on each side and a column separa-
gs = fig.add_gridspec(3, 3) tion of 1cm. The width of a figure is (21 - 2*2 - 1)/2 = 8cm.
ax.fill_betweenx([-1,1],[0],[2*[Link]])
ax = fig.add_subplot(gs[0, :]) One inch being 2.54cm, figure size should be 3.15×3.15 in.
[Link](0, -1, r” Period $\Phi$”)
ax.set_facecolor(”#ddddff”)
fig = [Link](figsize=(3.15,3.15), dpi=50)
1 [Link](”[Link]”, dpi=600)
fig, ax = [Link]() 0
[Link][”top”].set_color(”None”) 1 Period Matplotlib 3.5.0 handout for intermediate users. Copyright (c) 2021 Matplotlib De-
velopment Team. Released under a CC-BY 4.0 International License. Supported by
[Link][”right”].set_color(”None”) 0 5 10 15 20 25 30 NumFOCUS.
Matplotlib tips & tricks
Transparency Text outline Colorbar adjustment
Scatter plots can be enhanced by using transparency (al- Use text outline to make text more visible. You can adjust a colorbar’s size when adding it.
pha) in order to show area with higher density. Multiple scat-
import [Link] as fx im = [Link](Z)
ter plots can be used to delineate a frontier. text = [Link](0.5, 0.1, ”Label”)
text.set_path_effects([ cb = [Link](im,
X = [Link](-1, 1, 500) [Link](linewidth=3, foreground=’1.0’), fraction=0.046, pad=0.04)
Y = [Link](-1, 1, 500) [Link]()]) cb.set_ticks([])
[Link](X, Y, 50, ”0.0”, lw=2) # optional
[Link](X, Y, 50, ”1.0”, lw=0) # optional
[Link](X, Y, 40, ”C1”, lw=0, alpha=0.1)
呆鸟 㨄
图形解析 工作流
Matplotlib Matplotlib 绘图的基本步骤:
1 准备数据 2 创建图形 3 绘图 4 自定义设置 5 保存图形 6 显示图形
Axes/Subplot
天善智能 商业智能与大数据社区 [Link]
>>> import [Link] as plt
>>> x = [1,2,3,4] Step 1
>>> y = [10,20,25,30]
Matplotlib >>> fig = [Link]() Step 2
Y-axis Figure >>> ax = fig.add_subplot(111) Step 3
>>> [Link](x, y, color='lightblue', linewidth=3) Step 3, 4
Matplotlib 是 Python 的二维绘图库,用于生成符合出版质量或 >>> [Link]([2,4,6],
跨平台交互环境的各类图形。 [5,15,25],
color='darkgreen',
marker='^')
>>> ax.set_xlim(1, 6.5)
X-axis
>>> [Link]('[Link]')
一维数据 4 自定义图形
>>>
>>>
import numpy as np
x = [Link](0, 10, 100) 颜色、色条与色彩表 数学符号
>>> y = [Link](x) >>> [Link](x, x, x, x**2, x, x**3) >>> [Link](r'$sigma_i=15$', fontsize=20)
>>> z = [Link](x) >>> [Link](x, y, alpha = 0.4)
尺寸限制、图例和布局
二维数据或图片
>>> [Link](x, y, c='k')
>>> [Link](im, orientation='horizontal')
>>> im = [Link](img, 尺寸限制与自动调整
添加内边距
>>> data = 2 * [Link]((10, 10)) cmap='seismic') >>> [Link](x=0.0,y=0.1)
将图形纵横比设置为1
>>> data2 = 3 * [Link]((10, 10))
标记
>>> [Link]('equal')
设置x轴与y轴的限制
>>> Y, X = [Link][-[Link]j, -[Link]j]
>>> [Link](xlim=[0,10.5],ylim=[-1.5,1.5])
设置x轴的限制
>>> U = -1 - X**2 + Y
>>> ax.set_xlim(0,10.5)
图例
>>> V = 1 + X - Y**2 >>> fig, ax = [Link]()
>>> from [Link] import get_sample_data >>> [Link](x,y,marker=".")
>>> img = [Link](get_sample_data('axes_grid/bivariate_normal.npy')) >>> [Link](x,y,marker="o") >>> [Link](title='An Example Axes', 设置标题与x、y轴的标签
ylabel='Y-Axis',
线型 xlabel='X-Axis')
2 绘制图形 >>>
>>>
[Link](x,y,linewidth=4.0)
[Link](x,y,ls='solid')
>>> [Link](loc='best')
标记
自动选择最佳的图例位置
手动设置X轴刻度
>>> import [Link] as plt >>> [Link](ticks=range(1,5),
>>> [Link](x,y,ls='--')
画布
ticklabels=[3,100,-12,"foo"])
>>> [Link](x,y,'--',x**2,y**2,'-.') >>> ax.tick_params(axis='y', 设置Y轴长度与方向
>>> [Link](lines,color='r',linewidth=4.0) direction='inout',
>>> fig = [Link]()
文本与标注
length=10)
子图间距
>>> fig2 = [Link](figsize=[Link](2.0))
调整子图间距
坐标轴 >>> [Link](1,
-2.1,
>>> fig3.subplots_adjust(wspace=0.5,
hspace=0.3,
图形是以坐标轴为核心绘制的,大多数情况下,子图就可以满足需 'Example Graph', left=0.125,
求。子图是栅格系统的坐标轴。
style='italic') right=0.9,
>>> [Link]("Sine", top=0.9,
>>> fig.add_axes() xy=(8, 0), bottom=0.1)
>>> ax1 = fig.add_subplot(221) # row-col-num xycoords='data', >>> fig.tight_layout() 设置画布的子图布局
坐标轴边线
xytext=(10.5, 0),
>>> ax3 = fig.add_subplot(212) textcoords='data',
>>> fig3, axes = [Link](nrows=2,ncols=2) arrowprops=dict(arrowstyle="->", >>> [Link]['top'].set_visible(False) 隐藏顶部坐标轴线
>>> fig4, axes2 = [Link](ncols=3) connectionstyle="arc3"),) >>> [Link]['bottom'].set_position(('outward',10)) 设置底部边线的位置为outward
3 绘图例程 5 保存
一维数据 向量场 保存画布
>>> [Link]('[Link]')
为坐标轴添加箭头
保存透明画布
>>> fig, ax = [Link]() >>> axes[0,1].arrow(0,0,0.5,0.5)
>>> lines = [Link](x,y) 用线或标记连接点 >>> axes[1,1].quiver(y,z) 二维箭头
>>> [Link](x,y) 缩放或着色未连接的点 >>> axes[0,1].streamplot(X,Y,U,V) 二维箭头 >>> [Link]('[Link]', transparent=True)
>>> axes[0,0].bar([1,2,3],[3,4,5]) 绘制等宽纵向矩形
绘制等高横向矩形 数据分布 显示图形
>>>
>>>
>>>
axes[1,0].barh([0.5,1,2.5],[0,1,2])
axes[1,1].axhline(0.45)
axes[0,1].axvline(0.65)
绘制与轴平行的横线
绘制与轴垂直的竖线 >>> [Link](y) 直方图
6
绘制填充多边形 箱形图
>>> [Link](x,y,color='blue') >>> [Link](y) >>> [Link]()
>>> ax.fill_between(x,y,color='yellow') 填充y值和0之间 小提琴图
关闭与清除
>>> [Link](z)
二维数据或图片
清除坐标轴
二维数组伪彩色图
>>> fig, ax = [Link]() >>> [Link]()
清除画布
>>> axes2[0].pcolor(data2)
>>> im = [Link](img, 色彩表或RGB数组 >>> [Link]()
cmap='gist_earth', >>> axes2[0].pcolormesh(data) 二维数组等高线伪彩色图 >>> [Link]() 关闭窗口
>>> CS = [Link](Y,X,U)
interpolation='nearest',
>>> axes2[2].contourf(data1) 等高线图
原文作者
vmin=-2, DataCamp
vmax=2) >>> axes2[2]= [Link](CS) 等高线图标签 Learn Python for Data Science Interactively
Matplotlib 2.0.0 - Updated on: 02/2017
Python 数据科学 速查表
3 使用 Seaborn 绘图
坐标轴栅格
Seaborn
呆鸟 译
各类图形 回归图
使用下列别名导入该库: 绘制与线性回归模型拟合的数据
散点图
>>> [Link](x="sepal_width",
含分类变量的散点图
>>> import [Link] as plt y="sepal_length",
>>> [Link](x="species",
>>> import seaborn as sns data=iris,
y="petal_length",
data=iris) ax=ax)
使用 Seaborn 创建图形的基本步骤: >>> [Link](x="species",
不重叠分类散点图 分布图
1.准备数据
y="petal_length",
>>> plot = [Link](data.y, 绘制单变量分布
2.设定画布外观
data=iris)
条形图 kde=False,
3.使用 Seaborn 绘图
color="b")
用散点图示符
矩阵图
>>> [Link](x="sex",
4.自定义图形 y="survived", 显示点估计值和置信区间
热力图
hue="class",
>>> [Link](uniform_data,vmin=0,vmax=1)
data=titanic)
>>> import [Link] as plt 计数图
显示观测数量
>>>
>>>
>>>
import seaborn as sns
tips = sns.load_dataset("tips")
sns.set_style("whitegrid") 第2步
第1步
>>> [Link](x="deck",
data=titanic,
4 深度自定义 参阅 Matplotlib
第3步 Axisgrid 对象
palette="Greens_d")
>>> g = [Link](x="tip", 点图
y="total_bill", 用柱状图 移除左框
显示点估计和置信区间
data=tips, >>> [Link](x="class", >>> [Link](left=True)
aspect=2) y="survived", >>> g.set_ylabels("Survived") 设置Y轴的标签
>>> g = (g.set_axis_labels("Tip","Total bill(USD)"). hue="sex", >>> g.set_xticklabels(rotation=45) 设置X轴刻度标签
data=titanic, 设置坐标轴标签
第4步
set(xlim=(0,10),ylim=(0,100))) >>> g.set_axis_labels("Survived",
>>> [Link]("title") palette={"male":"g", "Sex")
>>> [Link](g) 第5步
"female":"m"}, >>> [Link](xlim=(0,5), 设置X与Y轴的限制和刻度
markers=["^","o"], ylim=(0,5),
linestyles=["-","--"]) xticks=[0,2.5,5],
箱型图
1 参阅列表、Numpy 及 Pandas
yticks=[0,2.5,5])
数据 箱形图
图形
>>> [Link](x="alive",
y="age",
添加图形标题
>>> import pandas as pd hue="adult_male",
>>> [Link]("A Title")
使用宽表数据的箱型图 调整y轴标签
>>> import numpy as np data=titanic)
>>> uniform_data = [Link](10, 12) >>> [Link]("Survived")
调整x轴标签
>>> [Link](data=iris,orient="h")
小提琴图
>>> data = [Link]({'x':[Link](1,101), >>> [Link]("Sex")
调整y轴限制
小提琴图
'y':[Link](0,4,100)}) >>> [Link](0,100)
调整x轴限制
Seaborn 提供了内置数据集:
>>> [Link](x="age", >>> [Link](0,10)
y="sex", >>> [Link](ax,yticks=[0,5]) 调整图形属性
>>> titanic = sns.load_dataset("titanic") hue="survived", >>> plt.tight_layout() 调整子图参数
>>> iris = sns.load_dataset("iris") data=titanic)
5 显示或保存图形 参阅 Matplotlib
2 画布外观 参阅 Matplotlib
>>> [Link]() 显示图形
上下文函数 >>> [Link]("[Link]") 将画布保存为图形
>>> f, ax = [Link](figsize=(5,6)) 创建画布与子图 >>> sns.set_context("talk") 将上下文设置为 "talk"
>>> [Link]("[Link]", 保存透明画布
transparent=True)
>>> sns.set_context("notebook", 将上下文设置为
Seaborn 样式 "notebook", 缩放字体,覆
关闭与清除 参阅 Matplotlib
font_scale=1.5,
rc={"[Link]":2.5}) 盖参数映射
>>> [Link]() 设置或重置 Seaborn 默认值
>>> sns.set_style("whitegrid")
设置 matplotlib 参数 调色板 >>> [Link]() 清除坐标轴
清除画布
定义调色板
>>> sns.set_style("ticks", >>> [Link]()
{"[Link]":8, >>> sns.set_palette("husl",3)
使用 with 临时设置调色板 >>> [Link]() 关闭窗口
"[Link]":8}) >>> sns.color_palette("husl")
返回参数字典或用with设置临时样式 >>>
>>> flatui = ["#9b59b6","#3498db","#95a5a6","#e74c3c","#34495e","#2ecc71"]
原文作者
>>> sns.axes_style("whitegrid")
sns.set_palette(flatui) 设置调色板 DataCamp
Learn Python for Data Science Interactively
Python 数据科学 速查表 3 渲染器与自定义可视化
Bokeh
呆鸟 译 图示符 栅格布局
散点标记 >>> from [Link] import gridplot
Python列表、Numpy数组、Pandas数据框或其它序列值
2. 创建图形
>>> color_mapper = CategoricalColorMapper(
factors=['US', 'Asia', 'Europe'], 4 输出与导出
3. 为数据添加渲染器,自定义可视化图
palette=['blue', 'red', 'green'])
>>> [Link]('mpg', 'cyl', source=cds_df, Notebook
4. 指定生成的输出类型 color=dict(field='origin',
5. 显示视图或保存结果 transform=color_mapper), >>> from [Link] import output_notebook, show
legend='Origin') >>> output_notebook()
HTML
>>> from [Link] import figure
>>> from [Link] import output_file, show 图例位置
脱机HTML
>>> x = [1, 2, 3, 4, 5]
绘图区内部
Step 1
>>> y = [6, 7, 2, 4, 5]
>>> p = figure(title="simple line example", Step 2 >>> from [Link] import file_html
>>> [Link] = 'bottom_left'
>>> from [Link] import CDN
绘图区外部
x_axis_label='x',
>>> html = file_html(p, CDN, "my_plot")
y_axis_label='y')
>>> [Link](x, y, legend="Temp.", line_width=2) Step 3 >>> from [Link] import Legend
>>> r1 = [Link]([Link]([1,2,3]), [Link]([3,2,1]) >>> from [Link] import output_file, show
>>> output_file("[Link]") Step 4 >>> r2 = [Link]([1,2,3,4], [3,4,5,6]) >>> output_file('my_bar_chart.html', mode='cdn')
>>> show(p) Step 5 >>> legend = Legend(items=[("One" ,[p1, r1]),("Two",[r2])],
组件
location=(0, -30))
>>> p.add_layout(legend, 'right')
1 数据 参阅列表、Numpy 及 Pandas
图例方向
>>> from [Link] import components
>>> script, div = components(p)
通常,Bokeh在后台把数据转换为列数据源,不过也可手动转换:
>>> [Link] = "horizontal" PNG
>>> import numpy as np >>> [Link] = "vertical"
>>> from [Link] import export_png
图例背景与边框
>>> import pandas as pd >>> export_png(p, filename="[Link]")
>>> df = [Link]([Link]([[33.9,4,65, 'US'],
SVG
[32.4,4,66, 'Asia'],
[21.4,4,109, 'Europe']]), >>> [Link].border_line_color = "navy"
columns=['mpg','cyl', 'hp', 'origin'], >>> [Link].background_fill_color = "white"
index=['Toyota', 'Fiat', 'Volvo']) >>> from [Link] import export_svgs
>>> from [Link] import ColumnDataSource 行列布局 >>> p.output_backend = "svg"
>>> export_svgs(p, filename="[Link]")
>>> cds_df = ColumnDataSource(df) 行
2 绘图
>>> from [Link] import row
>>> layout = row(p1,p2,p3) 5 显示或保存图形
>>> from [Link] import figure 列 >>> show(p1) >>> show(layout)
>>> p1 = figure(plot_width=300, tools='pan,box_zoom') >>> from [Link] import columns >>> save(p1) >>> save(layout)
行列嵌套
>>> p2 = figure(plot_width=300, plot_height=300, >>> layout = column(p1,p2,p3)
原文作者 DataCamp
x_range=(0, 8), y_range=(0, 8))
>>>layout = row(column(p1,p2), p3)
>>> p3 = figure() Learn Python for Data Science Interactively