Plotly作图基本命令(plotly Cheat Sheet)

最近刚开始学习Plotly的Python库,发现官方提供的Cheat Sheet也存在些小问题,整理了一下比较基本的命令,方便学习和使用。

预备工作

安装plotly包和插件

plotly的安装与其他包一样,通过pip安装:

1
pip install plotly

plotly绘制的图会上传到云端,如果希望离线作图则使用ploty.offline,这样在Jupyter Notebook中作图会产生本地的HTML。如果想让图表直接显示在Notebook中,可以加入以下命令:

init_notebook_mode(connected=True)

或者使用FigureWidget(需要导入plotly.graph_objs)。但是,上述做法在Juypter Lab中不能正常工作,也就是说plotly.offline无法在Jupyter Lab打开的Notebook中显示图表,为了解决这一问题,权宜之计是使用几个插件:

  • @jupyter-widgets/jupyterlab-manager
  • plotlywidget
  • @jupyterlab/plotly-extension

(具体哪个起什么作用不记得了。。)
安装的命令也很简单,例如对plotlywidget,安装命令为:

jupyter labextension install plotlywidget

更新:在plotly 4.x版本以后,plotly采用了新的chart-studio包来实现online模式的相关内容,plotly只保留了offline的功能,并且采用新的渲染框架和HTML输出模块实现offline的相关内容。具体的更新,参见其官方指南:https://plot.ly/python/v4-migration/

准备工作完成之后,就可以正式作图了。

导入包

1
2
3
import numpy as np
import plotly.graph_objs as go
import pandas as pd

注意:在Jupyter Lab中作图以后,如果直接将Notebook导出为markdown文件,那么plotly会采用静态图片的方式保存,如果我们想导出可以交互的动态图表,可以使用plotly.write_html()函数,将图片导出为html,其中涉及到是否保存完整的html、plotlyjs库的引用等,具体参见help

Basic Charts

Line Plots

1
2
3
4
5
6
7
trace0 = go.Scatter(
x=[1,2], y=[1,2])
trace1 = go.Scatter(
x=[1,2], y=[2,1])
f = go.Figure([trace0, trace1])
f.show()
f.write_html('001.html',full_html=False, include_plotlyjs='cdn')

Scatter Plots

1
2
3
4
5
6
7
trace = go.Scatter(
x=[1,2,3], y=[1,2,3],
text=['A','B','C'],
textposition='top center',
mode='markers+text')
data = [trace]
go.Figure(data)

Bar Charts

1
2
3
4
trace = go.Bar(
x=[1,2], y=[1,2])
data=[trace]
go.Figure(data)

Bubble Charts

1
2
3
4
5
6
trace = go.Scatter(
x=[1,2,3],y=[1,2,3],
marker=dict(
color=['red', 'blue', 'green'],
size=[30,80,120]), mode='markers')
go.Figure(trace)

Heatmaps

1
2
3
4
trace=go.Heatmap(
z=[[1,2,3,4],
[5,6,7,8]])
go.Figure(trace)

Area Plots

1
2
3
4
trace = go.Scatter(
x=[1,2], y=[1,2],
fill='tonexty')
go.Figure(trace)

Layout

Legends

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
trace0 = go.Scatter(
name='Calvin',
x=[1,2], y=[1,2])

trace1 = go.Scatter(
name='Hobbes',
x=[2,3], y=[2,1])

layout=go.Layout(
showlegend=True,
legend=dict(
x=0.2, y=0.5))

data=[trace0, trace1]
fig = go.Figure(data=data, layout=layout)
fig.show()

Axes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
trace = go.Scatter(
x=[1,2,3,4],
y=[1,2,3,6])

axis_template = dict(
showgrid=False,
zeroline=False,
nticks=20,
showline=True,
title='AXIS',
mirror='all')

layout=go.Layout(
xaxis=axis_template,
yaxis=axis_template)

data = [trace]
fig = go.Figure(
data=data,
layout=layout)

fig.show()

Statistical Charts

Histograms

1
2
3
trace = go.Histogram(
x = [1,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,5,5,6])
go.Figure(trace)

Box Plots

1
2
3
trace = go.Box(
x=[1,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,5,5,6])
go.Figure(trace)

2D Histogram

1
2
3
4
5
trace = go.Histogram2d(
x = [1,3,1,2,2,2,2,3,3,3,4,3,3,4,2,4,5,5,6],
y = [1,1,1,4,3,2,1,3,2,5,3,8,3,4,4,5,6,5,6]
)
go.Figure(trace)

Maps

Bubble Map

1
2
3
4
5
6
7
8
trace = dict(
type='scattergeo',
lon=[10,120], lat=[0, 40],
marker = dict(
color=['red', 'blue'],
size=[30,50]),
mode='markers')
go.Figure(trace)

Choropleth Map

1
2
3
4
5
6
7
8
9
trc = dict(
type='choropleth',
locations=['AZ', 'CA', 'VT'],
locationmode='USA-states',
colorscale='Viridis',
z=[10,20,40])
layout = dict(geo=dict(scope='usa'))
map = go.Figure(data=[trc], layout=layout)
map.show()

Scatter Map

1
2
3
4
trace = dict(
type='scattergeo',
lon=[42, 120], lat=[12, 40])
go.Figure(trace)

3D Charts

3D Surface Plots

1
2
3
4
5
trace = go.Surface(
colorscale='Viridis',
z=[[3,5,8,13],
[21,13,8,5]])
go.Figure(trace)

3D Line Plots

1
2
3
4
5
6
trace = go.Scatter3d(
x=[9,8,5,1],
y=[1,2,4,8],
z=[11,8,15,3],
mode='lines')
go.Figure(trace)

3D Scatter Plots

1
2
3
4
5
6
trace = go.Scatter3d(
x=[9,8,5,1],
y=[1,2,4,8],
z=[11,8,15,3],
mode='markers')
go.Figure(trace)

Figure Hirarchy

plotly的类和参数的结构可以表示如下面的层级:

  • Figure{}
    • Data[]
      • Trace{}
        • x,y,z[]
        • color, text, size[]
        • colorscale ‘ABC’ or []
        • marker{}
          • color ‘ABC’
          • symbol ‘ABC’
          • line{}
            • color ‘ABC’
            • width 123
    • Layout{}
      • title ‘ABC’
      • XAXIS, YAXIS{}
      • SCENE{}
        • XAXIS, YAXIS{}
      • GEO{}
      • LEGEND{}
      • ANNOTATIONS{}

其中,
{} = dictionary
[] = list
‘ABC’ = string
123 = number*