Matplotlib Bokeh Seaborn
Matplotlib Bokeh Seaborn
fig, ax = plt.subplots()
ax.errorbar(X, Y, Y∕4)
1 ax2.plot(Y2, X, color=”C0”)
21
1.0 fig.suptitle(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-
ax.plot(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 = np.linspace(0, 10, 100)
Y = np.sin(X) 432 Explore
Matplotlib offers several kind of plots (see Gallery): ax.plot(X, Y, color=”black”)
1 Figures are shown with a graphical user interface that al-
X = np.random.uniform(0, 1, 100) 765 X = np.linspace(0, 10, 100) 765 1234567 lows to zoom and pan the figure, to navigate between the
Y = np.random.uniform(0, 1, 100) 432 Y = np.sin(X) 432 different views and to show the value under the mouse.
ax.scatter(X, Y)
1 ax.plot(X, Y, linestyle=”--”)
1
X = np.arange(10) 765 1234567 X = np.linspace(0, 10, 100) 765 1234567 Save (bitmap or vector format)
Y = np.random.uniform(1, 10, 10) 432 Y = np.sin(X) 432
ax.bar(X, Y)
1 ax.plot(X, Y, linewidth=5)
1 fig.savefig(”my-first-figure.png”, dpi=300)
fig.savefig(”my-first-figure.pdf”)
Z = np.random.uniform(0, 1, (8,8)) 765 1234567 X = np.linspace(0, 10, 100) 765 1234567
432 Y = np.sin(X) 432
1 1
Matplotlib 3.5.0 handout for beginners. Copyright (c) 2021 Matplotlib Development
ax.imshow(Z) ax.plot(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 mpl.ticker import MultipleLocator as ML ax.plot(X, np.sin(X), ”C0”, label=”Sine”)
from mpl.ticker import ScalarFormatter as SF ax.plot(X, np.cos(X), ”C1”, label=”Cosine”)
4
Anatomy of a figure ax.xaxis.set_minor_locator(ML(0.2)) ax.legend(bbox_to_anchor=(0,1,1,.1),ncol=2,
Title Blue signal ax.xaxis.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 = np.linspace(0.1, 10*np.pi, 1000) Annotation
Y axis label
2 Y = np.sin(X)
ax.plot(X, Y, ”C1o:”, markevery=25, mec=”1.0”) ax.annotate(”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 = plt.subplots()
Minor tick label
X axis label ax.set_xscale(”log”)
ax.plot(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 = plt.subplots(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*np.pi])
ax = fig.add_subplot(gs[0, :]) One inch being 2.54cm, figure size should be 3.15×3.15 in.
ax.text(0, -1, r” Period $\Phi$”)
ax.set_facecolor(”#ddddff”)
fig = plt.figure(figsize=(3.15,3.15), dpi=50)
1 plt.savefig(”figure.pdf”, dpi=600)
fig, ax = plt.subplots() 0
ax.spines[”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
ax.spines[”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 matplotlib.patheffects as fx im = ax.imshow(Z)
ter plots can be used to delineate a frontier. text = ax.text(0.5, 0.1, ”Label”)
text.set_path_effects([ cb = plt.colorbar(im,
X = np.random.normal(-1, 1, 500) fx.Stroke(linewidth=3, foreground=’1.0’), fraction=0.046, pad=0.04)
Y = np.random.normal(-1, 1, 500) fx.Normal()]) cb.set_ticks([])
ax.scatter(X, Y, 50, ”0.0”, lw=2) # optional
ax.scatter(X, Y, 50, ”1.0”, lw=0) # optional
ax.scatter(X, Y, 40, ”C1”, lw=0, alpha=0.1)
呆鸟 㨄
图形解析 工作流
Matplotlib Matplotlib 绘图的基本步骤:
1 准备数据 2 创建图形 3 绘图 4 自定义设置 5 保存图形 6 显示图形
Axes/Subplot
天善智能 商业智能与大数据社区 www.hellobi.com
>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4] Step 1
>>> y = [10,20,25,30]
Matplotlib >>> fig = plt.figure() Step 2
Y-axis Figure >>> ax = fig.add_subplot(111) Step 3
>>> ax.plot(x, y, color='lightblue', linewidth=3) Step 3, 4
Matplotlib 是 Python 的二维绘图库,用于生成符合出版质量或 >>> ax.scatter([2,4,6],
跨平台交互环境的各类图形。 [5,15,25],
color='darkgreen',
marker='^')
>>> ax.set_xlim(1, 6.5)
X-axis
>>> plt.savefig('foo.png')
一维数据 4 自定义图形
>>>
>>>
import numpy as np
x = np.linspace(0, 10, 100) 颜色、色条与色彩表 数学符号
>>> y = np.cos(x) >>> plt.plot(x, x, x, x**2, x, x**3) >>> plt.title(r'$sigma_i=15$', fontsize=20)
>>> z = np.sin(x) >>> ax.plot(x, y, alpha = 0.4)
尺寸限制、图例和布局
二维数据或图片
>>> ax.plot(x, y, c='k')
>>> fig.colorbar(im, orientation='horizontal')
>>> im = ax.imshow(img, 尺寸限制与自动调整
添加内边距
>>> data = 2 * np.random.random((10, 10)) cmap='seismic') >>> ax.margins(x=0.0,y=0.1)
将图形纵横比设置为1
>>> data2 = 3 * np.random.random((10, 10))
标记
>>> ax.axis('equal')
设置x轴与y轴的限制
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> ax.set(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 = plt.subplots()
>>> from matplotlib.cbook import get_sample_data >>> ax.scatter(x,y,marker=".")
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy')) >>> ax.plot(x,y,marker="o") >>> ax.set(title='An Example Axes', 设置标题与x、y轴的标签
ylabel='Y-Axis',
线型 xlabel='X-Axis')
2 绘制图形 >>>
>>>
plt.plot(x,y,linewidth=4.0)
plt.plot(x,y,ls='solid')
>>> ax.legend(loc='best')
标记
自动选择最佳的图例位置
手动设置X轴刻度
>>> import matplotlib.pyplot as plt >>> ax.xaxis.set(ticks=range(1,5),
>>> plt.plot(x,y,ls='--')
画布
ticklabels=[3,100,-12,"foo"])
>>> plt.plot(x,y,'--',x**2,y**2,'-.') >>> ax.tick_params(axis='y', 设置Y轴长度与方向
>>> plt.setp(lines,color='r',linewidth=4.0) direction='inout',
>>> fig = plt.figure()
文本与标注
length=10)
子图间距
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))
调整子图间距
坐标轴 >>> ax.text(1,
-2.1,
>>> fig3.subplots_adjust(wspace=0.5,
hspace=0.3,
图形是以坐标轴为核心绘制的,大多数情况下,子图就可以满足需 'Example Graph', left=0.125,
求。子图是栅格系统的坐标轴。
style='italic') right=0.9,
>>> ax.annotate("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 = plt.subplots(nrows=2,ncols=2) arrowprops=dict(arrowstyle="->", >>> ax1.spines['top'].set_visible(False) 隐藏顶部坐标轴线
>>> fig4, axes2 = plt.subplots(ncols=3) connectionstyle="arc3"),) >>> ax1.spines['bottom'].set_position(('outward',10)) 设置底部边线的位置为outward
3 绘图例程 5 保存
一维数据 向量场 保存画布
>>> plt.savefig('foo.png')
为坐标轴添加箭头
保存透明画布
>>> fig, ax = plt.subplots() >>> axes[0,1].arrow(0,0,0.5,0.5)
>>> lines = ax.plot(x,y) 用线或标记连接点 >>> axes[1,1].quiver(y,z) 二维箭头
>>> ax.scatter(x,y) 缩放或着色未连接的点 >>> axes[0,1].streamplot(X,Y,U,V) 二维箭头 >>> plt.savefig('foo.png', 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)
绘制与轴平行的横线
绘制与轴垂直的竖线 >>> ax1.hist(y) 直方图
6
绘制填充多边形 箱形图
>>> ax.fill(x,y,color='blue') >>> ax3.boxplot(y) >>> plt.show()
>>> ax.fill_between(x,y,color='yellow') 填充y值和0之间 小提琴图
关闭与清除
>>> ax3.violinplot(z)
二维数据或图片
清除坐标轴
二维数组伪彩色图
>>> fig, ax = plt.subplots() >>> plt.cla()
清除画布
>>> axes2[0].pcolor(data2)
>>> im = ax.imshow(img, 色彩表或RGB数组 >>> plt.clf()
cmap='gist_earth', >>> axes2[0].pcolormesh(data) 二维数组等高线伪彩色图 >>> plt.close() 关闭窗口
>>> CS = plt.contour(Y,X,U)
interpolation='nearest',
>>> axes2[2].contourf(data1) 等高线图
原文作者
vmin=-2, DataCamp
vmax=2) >>> axes2[2]= ax.clabel(CS) 等高线图标签 Learn Python for Data Science Interactively
Matplotlib 2.0.0 - Updated on: 02/2017
Python 数据科学 速查表
3 使用 Seaborn 绘图
坐标轴栅格
Seaborn
呆鸟 译
各类图形 回归图
使用下列别名导入该库: 绘制与线性回归模型拟合的数据
散点图
>>> sns.regplot(x="sepal_width",
含分类变量的散点图
>>> import matplotlib.pyplot as plt y="sepal_length",
>>> sns.stripplot(x="species",
>>> import seaborn as sns data=iris,
y="petal_length",
data=iris) ax=ax)
使用 Seaborn 创建图形的基本步骤: >>> sns.swarmplot(x="species",
不重叠分类散点图 分布图
1.准备数据
y="petal_length",
>>> plot = sns.distplot(data.y, 绘制单变量分布
2.设定画布外观
data=iris)
条形图 kde=False,
3.使用 Seaborn 绘图
color="b")
用散点图示符
矩阵图
>>> sns.barplot(x="sex",
4.自定义图形 y="survived", 显示点估计值和置信区间
热力图
hue="class",
>>> sns.heatmap(uniform_data,vmin=0,vmax=1)
data=titanic)
>>> import matplotlib.pyplot as plt 计数图
显示观测数量
>>>
>>>
>>>
import seaborn as sns
tips = sns.load_dataset("tips")
sns.set_style("whitegrid") 第2步
第1步
>>> sns.countplot(x="deck",
data=titanic,
4 深度自定义 参阅 Matplotlib
第3步 Axisgrid 对象
palette="Greens_d")
>>> g = sns.lmplot(x="tip", 点图
y="total_bill", 用柱状图 移除左框
显示点估计和置信区间
data=tips, >>> sns.pointplot(x="class", >>> g.despine(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",
>>> plt.title("title") palette={"male":"g", "Sex")
>>> plt.show(g) 第5步
"female":"m"}, >>> h.set(xlim=(0,5), 设置X与Y轴的限制和刻度
markers=["^","o"], ylim=(0,5),
linestyles=["-","--"]) xticks=[0,2.5,5],
箱型图
1 参阅列表、Numpy 及 Pandas
yticks=[0,2.5,5])
数据 箱形图
图形
>>> sns.boxplot(x="alive",
y="age",
添加图形标题
>>> import pandas as pd hue="adult_male",
>>> plt.title("A Title")
使用宽表数据的箱型图 调整y轴标签
>>> import numpy as np data=titanic)
>>> uniform_data = np.random.rand(10, 12) >>> plt.ylabel("Survived")
调整x轴标签
>>> sns.boxplot(data=iris,orient="h")
小提琴图
>>> data = pd.DataFrame({'x':np.arange(1,101), >>> plt.xlabel("Sex")
调整y轴限制
小提琴图
'y':np.random.normal(0,4,100)}) >>> plt.ylim(0,100)
调整x轴限制
Seaborn 提供了内置数据集:
>>> sns.violinplot(x="age", >>> plt.xlim(0,10)
y="sex", >>> plt.setp(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
>>> plt.show() 显示图形
上下文函数 >>> plt.savefig("foo.png") 将画布保存为图形
>>> f, ax = plt.subplots(figsize=(5,6)) 创建画布与子图 >>> sns.set_context("talk") 将上下文设置为 "talk"
>>> plt.savefig("foo.png", 保存透明画布
transparent=True)
>>> sns.set_context("notebook", 将上下文设置为
Seaborn 样式 "notebook", 缩放字体,覆
关闭与清除 参阅 Matplotlib
font_scale=1.5,
rc={"lines.linewidth":2.5}) 盖参数映射
>>> sns.set() 设置或重置 Seaborn 默认值
>>> sns.set_style("whitegrid")
设置 matplotlib 参数 调色板 >>> plt.cla() 清除坐标轴
清除画布
定义调色板
>>> sns.set_style("ticks", >>> plt.clf()
{"xtick.major.size":8, >>> sns.set_palette("husl",3)
使用 with 临时设置调色板 >>> plt.close() 关闭窗口
"ytick.major.size":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 bokeh.layouts import gridplot
Python列表、Numpy数组、Pandas数据框或其它序列值
2. 创建图形
>>> color_mapper = CategoricalColorMapper(
factors=['US', 'Asia', 'Europe'], 4 输出与导出
3. 为数据添加渲染器,自定义可视化图
palette=['blue', 'red', 'green'])
>>> p3.circle('mpg', 'cyl', source=cds_df, Notebook
4. 指定生成的输出类型 color=dict(field='origin',
5. 显示视图或保存结果 transform=color_mapper), >>> from bokeh.io import output_notebook, show
legend='Origin') >>> output_notebook()
HTML
>>> from bokeh.plotting import figure
>>> from bokeh.io 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 bokeh.embed import file_html
>>> p.legend.location = 'bottom_left'
>>> from bokeh.resources import CDN
绘图区外部
x_axis_label='x',
>>> html = file_html(p, CDN, "my_plot")
y_axis_label='y')
>>> p.line(x, y, legend="Temp.", line_width=2) Step 3 >>> from bokeh.models import Legend
>>> r1 = p2.asterisk(np.array([1,2,3]), np.array([3,2,1]) >>> from bokeh.io import output_file, show
>>> output_file("lines.html") Step 4 >>> r2 = p2.line([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 bokeh.embed import components
>>> script, div = components(p)
通常,Bokeh在后台把数据转换为列数据源,不过也可手动转换:
>>> p.legend.orientation = "horizontal" PNG
>>> import numpy as np >>> p.legend.orientation = "vertical"
>>> from bokeh.io import export_png
图例背景与边框
>>> import pandas as pd >>> export_png(p, filename="plot.png")
>>> df = pd.DataFrame(np.array([[33.9,4,65, 'US'],
SVG
[32.4,4,66, 'Asia'],
[21.4,4,109, 'Europe']]), >>> p.legend.border_line_color = "navy"
columns=['mpg','cyl', 'hp', 'origin'], >>> p.legend.background_fill_color = "white"
index=['Toyota', 'Fiat', 'Volvo']) >>> from bokeh.io import export_svgs
>>> from bokeh.models import ColumnDataSource 行列布局 >>> p.output_backend = "svg"
>>> export_svgs(p, filename="plot.svg")
>>> cds_df = ColumnDataSource(df) 行
2 绘图
>>> from bokeh.layouts import row
>>> layout = row(p1,p2,p3) 5 显示或保存图形
>>> from bokeh.plotting import figure 列 >>> show(p1) >>> show(layout)
>>> p1 = figure(plot_width=300, tools='pan,box_zoom') >>> from bokeh.layouts 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