programmingPlotly

plotly 使用入门

2019-03-22  本文已影响0人  小白小白啦

这两天看了一下数据可视化工具plotly,感觉还不错,比matplotlib炫酷多了,在此记录一下简单用法。

介绍plotly

plotly是一款基于D3.js框架的Python库,所以功能肯定很强大、炫酷。结合jupyter notebook效果更好。pip安装

pip install plotly

以为pip安装一下就行了,迫不及待就去跑示例代码,结果报错,提示没有登录什么的,了解之后才知道,plotly有两种模式。

离线模式:没有数量限制,图片都在本地。
在线模式:最多可以上传25张,可以通过浏览器在线编辑、观看。更好的分享给别,有分为三种情况——公开(public)、私人(private)、秘密(secret)。

在线plotly

首先需要注册一个plotly的账户,然后可以看到自己的UsernameAPI Keys,放到代码里面就可以作图了。

import plotly 
plotly.tools.set_credentials_file(username='yourAccount', api_key='u8U00uFdqKcYH5qykuu4')

plotly.tools.set_config_file(world_readable=True,
                             sharing='public')

import plotly.plotly as py
import plotly.graph_objs as go

trace0 = go.Scatter(
    x=[1, 2, 3, 4],
    y=[10, 15, 13, 17]
)
trace1 = go.Scatter(
    x=[1, 2, 3, 4],
    y=[16, 5, 11, 9]
)
data = [trace0, trace1]

py.plot(data, filename = 'basic-line', auto_open=True)

上面会输出一个网址,打开就可以看到了。最厉害的是竟然可以直接在线可视化编辑,厉害了!更多功能自己点击左侧按钮实验吧。


在线编辑

离线模式

大部分我们还是使用离线模式,比较在线模式有数量限制,还得打开网页才能看到,其中离线模式我喜欢在jupyter notebook中使用。

import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

plot([go.Scatter(x=[1, 2, 3], y=[3, 1, 6])])

输出'file:///data/notebook/dataVisualization/temp-plot.html',是一个HTML,不是很方便,使用iplot画图就方便多了

init_notebook_mode(connected=True)# 设置为离线模式
iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}])

直接输出图片了。

举几个例子

在jupyter notebook输出会有缩放、移动、截图等功能按钮,但是markdown不能显示,就简单截个图吧。
Plotly的核心是一个数据可视化工具箱,每个plotly图像的背后都是一个JSON对象,一个类似字典的数据结构。仅仅通过修改这个对象的一些关键字,就可以得到非常不同的、详细的图。例如:

import plotly.offline as py
import plotly.graph_objs as go

py.init_notebook_mode(connected=True)

trace1 = go.Scatter(x=[1,2,3], y=[4,5,6], marker={'color': 'red', 'symbol': 104, 'size': 10}, 
                    mode="markers+lines",  text=["one","two","three"], name='1st Trace')
                                               
layout=go.Layout(title="First Plot", xaxis={'title':'x1'}, yaxis={'title':'x2'})
figure=go.Figure(data=[trace1],layout=layout)
py.iplot(figure, filename='pyguide_1')
first plot
figure

输出

Figure({
    'data': [{'marker': {'color': 'red', 'size': 10, 'symbol': 104},
              'mode': 'markers+lines',
              'name': '1st Trace',
              'text': [one, two, three],
              'type': 'scatter',
              'uid': '6e76d08b-2f9b-429e-ae31-0d2faeb41e78',
              'x': [1, 2, 3],
              'y': [4, 5, 6]}],
    'layout': {'title': {'text': 'First Plot'}, 'xaxis': {'title': {'text': 'x1'}}, 'yaxis': {'title': {'text': 'x2'}}}
})

可以看到我们使用py.iplot画的图确实是一个类似于字典的对象,此外,我们可以通过添加/定义与散点图相关的关键字的值,来修改这个图片。
如果我们想改变散点图的标题,同时使用绿色的先代替红色的先,可以通过Plot update来实现。

figure.update(dict(layout=dict(title='Plot update'), data=[dict(marker=dict(color='blue'))]))
py.iplot(figure, filename='pyguide_2')
plot update

此外,Plotly plots 是交互式的,这意味着你可以在图像上通过平移、选择、缩放来手动操作探索数据。

很快你就能弄明白如何以你想要的方式绘制图表,怎么分享这些信息给你想分享的人。例如,我们可以快速查看一下如何定义生成散点图所需的对象,以比较两个大陆之间的预期寿命了人均GDP。

import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/yankev/test/master/life-expectancy-per-GDP-2007.csv')

americas = df[(df.continent=='Americas')]
europe = df[(df.continent=='Europe')]

trace_comp0 = go.Scatter(
    x=americas.gdp_percap,
    y=americas.life_exp,
    mode='markers',
    marker=dict(size=12,
                line=dict(width=1),
                color="navy"
               ),
    name='Americas',
    text=americas.country,
    )

trace_comp1 = go.Scatter(
    x=europe.gdp_percap,
    y=europe.life_exp,
    mode='markers',
    marker=dict(size=12,
                line=dict(width=1),
                color="red"
               ),
    name='Europe',
    text=europe.country,
        )

data_comp = [trace_comp0, trace_comp1]
layout_comp = go.Layout(
    title='Life Expectancy v. Per Capita GDP, 2007',
    hovermode='closest',
    xaxis=dict(
        title='GDP per capita (2000 dollars)',
        ticklen=5,
        zeroline=False,
        gridwidth=2,
    ),
    yaxis=dict(
        title='Life Expectancy (years)',
        ticklen=5,
        gridwidth=2,
    ),
)
fig_comp = go.Figure(data=data_comp, layout=layout_comp)
py.iplot(fig_comp, filename='life-expectancy-per-GDP-2007')
Life Expectancy v. Per Capita GDP, 2007

希望这能让您了解如果使用Plotly Python Library绘制图表,稍后,我们将在后面的章节详细介绍构成这个图表的不同部分。但是现在,我希望您能看到它的可定制性,以及我们如何通过编程定义这些图。

Plotly强大能力的来源

Plotly生成的所有图表实际上都是plotly.js这个javascript库产生的,无论是在浏览器还是Ipython notebook中,所有的可视化、交互都是基于plot.js,plot.js建立在d3.js和stack.gl之上,plotly.js是一个高级的声明性图表库,提供了20多种图表类型,包含了3D图表、统计图和SVG地图。

使用Python API

Python API是一个设计用来和Plotly.js库交互的包,以便允许Python用户在他们喜欢的环境中创建绘图。这个包提供函数和图形对象,可以简化图形生成的过程,这相当于在JSON对象中正确定义关键字(如上面的例子所示),这将允许我们以函数的方式创建我们的图。所以我们来分解一下。

import plotly.offline as py
import plotly.graph_objs as go

为了生成我们的Plotly图表,我们需要两个主要的模块。
. plotly.offline包含了与Plotly服务器通信的功能。
. plotly.graph_objs 包含了生成图表对象的函数
注意:如果我们检查上一节中的示例代码,我们可以看到下面的部分。
. Data
. Layout
. Figure

DATA

go.Scatter(x=[1,2,3], y=[4,5,6], marker={'color': 'red', 'symbol': 104, 'size': "10"}, 
                                               mode="markers+lines",  text=["one","two","three"])

输出

Scatter({
    'marker': {'color': 'red', 'size': 10, 'symbol': 104},
    'mode': 'markers+lines',
    'text': [one, two, three],
    'x': [1, 2, 3],
    'y': [4, 5, 6]
})

定义了一个散点图的轨迹,此外,它定制了我们需要绘制的数据,即3个数据点(1,4),(2,5),(3,6),以及绘制该数据相关的规范。在这个例子中,我们想把这些点画成空闲的x,用红色的线把他们串起来。
此外,我们还可以向数据列表中,添加另一个散点对象,我们可以通过定义一个新的散点对象来实现这一点,并将其包含到数据对象的定义中。

import numpy as np
x = np.arange(1,3.2,0.2)
y = 6*np.sin(x)
y

输出

array([5.04882591, 5.59223452, 5.91269838, 5.99744162, 5.84308579,
       5.45578456, 4.85097842, 4.05277908, 3.09300823, 2.0099289 ,
       0.84672005])

输出

trace2 = go.Scatter(x=x, y=y, marker={'color': 'blue', 'symbol': 'star', 'size': 10}, mode='markers', name='2nd trace')
data = go.Data([trace1, trace2])
data

输出

[Scatter({
     'marker': {'color': 'red', 'size': 10, 'symbol': 104},
     'mode': 'markers+lines',
     'name': '1st Trace',
     'text': [one, two, three],
     'x': [1, 2, 3],
     'y': [4, 5, 6]
 }), Scatter({
     'marker': {'color': 'blue', 'size': 10, 'symbol': 'star'},
     'mode': 'markers',
     'name': '2nd trace',
     'x': array([1. , 1.2, 1.4, 1.6, 1.8, 2. , 2.2, 2.4, 2.6, 2.8, 3. ]),
     'y': array([5.04882591, 5.59223452, 5.91269838, 5.99744162, 5.84308579, 5.45578456,
                 4.85097842, 4.05277908, 3.09300823, 2.0099289 , 0.84672005])
 })]
plot2 = py.iplot(go.Figure(data=data, layout=layout), filename='pyguide_3')
plot2
First Plot

Layout

这个Layout就是定义图的外观,以及与数据无关的图功能。因此,我们可以改变标题、轴标题、间距、字体等。

layout=go.Layout(title="First Plot", xaxis={'title':'x1'}, yaxis={'title':'x2'})
layout

输出

{'title': 'First Plot', 'xaxis': {'title': 'x1'}, 'yaxis': {'title': 'x2'}}

Annotations

我们为轴添加了标题,还添加一个一个文本注释,指出最大点。

layout.update(dict(annotations=[go.Annotation(text="Highest Point", x=3, y=6)]))
py.iplot(go.Figure(data=data, layout=layout), filename='pyguide_4')
First Plot

推荐一篇与pandas结合的文章,写的很好。The Next Level of Data Visualization in Python

参考

Getting Started with Plotly for Python
Plotly User Guide in Python
官方文档

上一篇下一篇

猜你喜欢

热点阅读