Plotly学习笔记

Plotly介绍

  • Plotly是一个基于JavaScript的绘图库,Plotly绘图种类丰富,效果美观。
  • 易于保存和分享,Plotly的绘图结果可以与Web无缝集成。
  • Plotly默认的绘图结果是一个HTML网页文件,通过浏览器可以查看。

Plotly绘图命令

在真实项目中,使用Plotly进行绘图的完整流程包括:

  • 添加图轨数据trace
  • 设置画图布局,使用plotly.graph_objs.Layout命令
  • 集成图形、布局数据
  • 绘制图形输出,用plotly.offline.plot()或者在jupyter notebook环境下用plotly.offline.iplot()进行离线绘制

散点图/折线图

图轨数据trace本质上是个字典,由于是绘制散点图,在这里要用到plotly.graph_objs.Scatter()函数创建散点图类的trace。trace包含的常用的键如下:

键值含义
x list类型;横坐标变量
y list类型;纵坐标变量
name 图例名称
text list类型;元素标识
textposition 标识位置
mode ‘markers’表示点;‘lines‘表示折线;’text‘标识标识文本;可以用’+‘号将两种模式结合起来
connectgaps bool类型;是否连接缺失值
color 颜色
opacity 透明度,值为0~1

可以创建多个trace作为输出图中的多组数据,设置完trace后,将所有trace数据集成于一个列表中,作为图形数据对象。

然后可以开始用plotly.graph_objs.Layout命令进行画面布局。其常用参数如下:

参数名 参数含义
title 图表标题
xaxis dict类型;{title:横坐标名称}
yaxis dict类型;{title:纵坐标名称}
showlegend bool类型;是否显示图例
legend dict类型;图例在图象中的位置;{x:横坐标的比例(<=1),y:纵坐标的比例(<=1)}
font dict类型;字体样式和大小;{size:字体大小}

设置好布局后,就可以将trace和layout两个字典用plotly.graph_objs.Figure()集成在一起,结果将传给我们选择的绘图函数,最后将其用plotly.offline.plot()或在jupyter notebook环境下用plotly.offline.iplot()进行离线输出即可。

关于两个输出函数的差别

虽然plotly.offline.plot()plotly.offline.iplot()两个函数都是离线输出图象的方法,但plot()会生成一个离线的html文件,里面放置图片,iplot()则直接在ipython notebook里面生成图片。

当在notebook中编译时,若要设置默认输出模式,可以在前面加上下面这句代码:

1
plotly.offline.init_notebook_mode(connected=True)

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import plotly as py
import plotly.graph_objs as go

text=[]
for i in range(15):
    s='t'+str(i+1)
    text.append(s)

trace1 = go.Scatter(
    x=[1, 2, 3, 4, 5,
       6, 7, 8, 9, 10,
       11, 12, 13, 14, 15],
    y=[10, 20, None, 15, 10,
       5, 15, None, 20, 10,
       10, 15, 25, 20, 10],
    text=text,
    textposition='top center',
    mode='markers+text+lines',
    name='<b>No</b> Gaps',  # Style name/legend entry with html tags
    connectgaps=True #是否连接缺失值
)
trace2 = go.Scatter(
    x=[1, 2, 3, 4, 5,
       6, 7, 8, 9, 10,
       11, 12, 13, 14, 15],
    y=[5, 15, None, 10, 5,
       0, 10, None, 15, 5,
       5, 10, 20, 15, 5],
    name='Gaps',
    opacity=0.5
)

data = [trace1, trace2]

fig = dict(data=data)
py.offline.plot(fig, filename='simple-connectgaps.html')

运行后系统会自动用默认浏览器打开html文件,互动式展现图象。
在这里插入图片描述
若想改变html文件的存储路径,可以直接在plotly.offline.plot()或在plotly.offline.iplot()中的filename中修改,但这样每次都要将路径输入一遍,所以可以采用切换工作目录的方式,以省去不必要的操作,具体做法如下:

1
2
import os
os.chdir('your filepath')

柱状图

柱状图的图轨数据结构与散点图的相似,这里用plotly.graph_objs.Bar()函数创建图轨数据。经上面的方法绘制图象。

Tips:关于DataFrame类型的数据

DataFrame中存储的数据类型为系列(series),而Plotly图轨数据类型要求为列表(list)。

1
2
In[16]: type(df3['Price'])
Out[16]: pandas.core.series.Series

所以需要用到tolist()函数将其转化成list类型。

1
2
In[17]: type(df3['Price'].tolist())
Out[17]: list

并且,DataFrame中有索引值和元素值,当我们从DataFrame中取出数据进行柱状图绘制时,一般都是将索引值作为每组的区分。这时就可以用如下方法提取索引值和元素值:

1
2
df['row','column'].index
df['row','column'].values

然后就可以参照散点图的做法进行绘制。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'''
quantity_first10 =

Country
United Kingdom    4701272
Netherlands        200937
EIRE               147447
Germany            119263
France             112104
Australia           84209
Sweden              36083
Switzerland         30630
Spain               27951
Japan               26016
... ...
Name: Quantity, dtype: int64
'''
import plotly as py
import plotly.graph_objs as go

trace=[go.Bar(x=quantity_first10.index.tolist(),
              y=quantity_first10.values.tolist(),
              marker=dict(color='orange'),opacity=0.5)]
             
layout=go.Layout(title='购买商品数前十的国家',xaxis=dict(title='Country'))

figure=go.Figure(data=trace,layout=layout)
py.offline.plot(figure,auto_open=True)

运行后系统会自动用默认浏览器打开html文件,互动式展现图象。
在这里插入图片描述
当然也可以加上另一个图轨一起绘制:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
'''
Pricesum =

Country
Australia               1.385213e+05
Austria                 1.019868e+04
Bahrain                 7.541400e+02
Belgium                 4.119634e+04
Brazil                  1.143600e+03
Canada                  3.666380e+03
Channel Islands         2.045044e+04
Cyprus                  1.359038e+04
Czech Republic          8.267400e+02
... ...
Name: Price, dtype: float64
'''
trace=go.Bar(x=quantity_first10.index.tolist(),
             y=quantity_first10.values.tolist(),
             marker=dict(color='orange'),opacity=0.5,
             name='quantity first 10')
trace0=go.Bar(x=quantity_first10.index.tolist(),
              y=Pricesum[quantity_first10.index].tolist(),
              marker=dict(color='blue'),opacity=0.5,
              name='price of the quantity first 10')

layout=go.Layout(title='购买商品数前十的国家及其销售额',xaxis=dict(title='Country'))

figure=go.Figure(data=[trace,trace0],layout=layout)
py.offline.plot(figure,auto_open=True)

结果如下:
在这里插入图片描述
还可以设置Layout中的参数barmode,将其设为stack,即barmode='stack'可以得到如下效果:
在这里插入图片描述