Plotly 是一个交互式Html绘图工具,可以生成很多美观的交互式绘图,本文简单记录几个简单示例,以及如何将交互式绘图嵌入到Jupyter Notebook 内
更多绘图参考plotly python gallery
Table of Contents
Plotly 分为在线和离线两个版本,在线版本需要注册帐号后生成Key后用代码绑定
In [1]:
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
plotly.tools.set_credentials_file(
username='zodiac911', api_key='Y1SBr9acE8gCvmxlLftn')
In [2]:
N = 1000
random_x = np.random.randn(N)
random_y = np.random.randn(N)
# Create a trace
trace = go.Scatter(
x=random_x,
y=random_y,
mode='markers'
)
data = [trace]
# Plot and embed in ipython notebook!
# py.iplot(data, filename='basic-scatter')
# 在线版
plot_url = py.plot(data, filename='basic-line')
print(plot_url)
在线版生成的图保存在云端,考虑到天朝的网络环境,我选择使用离线版
为了在Notebook内绘图,需要使用交互式API,和普通版在API上的区别一般相差一个 i
. 如 plot
变为 iplot
开启 Jupyter notebook 交互模式,即可在Notebook内显示Html内容
In [3]:
from IPython.core.display import HTML
import plotly.offline as offline
offline.init_notebook_mode(connected=True)
Plotly Python API¶
In [4]:
import pandas as pd
import numpy as np
num_dropline = 5
data = pd.read_csv("data/data.csv") # 读取数据
data = data.iloc[num_dropline:] # 丢弃坏行
trace1 = go.Scatter(name='name', x=data["time"], y=data["name"])
trace2 = go.Scatter(name='action', x=data['time'], y=data["action"])
DATA = [trace1, trace2]
#layout = go.Layout(showlegend =True, legend=dict(x=1,y=1),xaxis = xaxis,yaxis = yaxis)
layout = go.Layout(showlegend=True, legend=dict(x=1, y=1), title="test")
fig = go.Figure(data=DATA, layout=layout)
offline.iplot(fig) # 交互式绘图使用 iplot
由于GitHub Pages 环境,博客无法展示Notebook内HTML内容,使用在线版本重新绘制
In [5]:
# 在线版
plot_url = py.plot(fig, filename='jupyter-parametric_plot')
print(plot_url)
Plotly API 非交互版¶
在本地生成Html文件
In [6]:
offline.plot(fig, filename='data/plotly.html') # 非 交互式绘图使用 plot,结果为 html 文件
Out[6]:
Matplotlib API¶
Matplotlib API 的好处是可以全部采用 Matplotlib 的写法,最后转换一下即可。
In [7]:
import matplotlib.pyplot as plt
import plotly.tools as tls
%matplotlib inline
fig, ax = plt.subplots()
ax.plot(data['time'], data["name"])
plt.show() # 用 matplot 画图
offline.iplot_mpl(fig) # 用 plotly 转换为交互式绘图
In [8]:
# 在线版
plot_url = py.plot_mpl(fig)
print(plot_url)
In [9]:
fig = plt.figure(figsize=(9, 6), dpi=100)
ax = fig.add_subplot(1, 1, 1, frameon=True) # aspect=1
t = np.linspace(0, 2*np.pi, 50, endpoint=False)
sins = np.sin(t)
coss = np.cos(t)
ax.plot(t, sins, 'r', alpha=0.5, lw=0.5, ls='-', marker='+', label='sin')
ax.plot(t, coss, 'g', alpha=0.5, lw=0.5, ls='-', marker='+', label='cos')
ax.set_ylim([-1.5, 1.5])
ax.set_xlim([-2, 8])
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title')
plt.show()
offline.iplot_mpl(fig) # 用 plotly 转换为交互式绘图
In [10]:
# 在线版
plot_url = py.plot_mpl(fig)
print(plot_url)
In [11]:
x = np.random.randn(2000)
y = np.random.randn(2000)
offline.iplot([go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')),
go.Scatter(x=x, y=y, mode='markers', marker=dict(color='white', size=3,
opacity=0.3))], show_link=False)
In [12]:
# 在线版
plot_url = py.plot([go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')),
go.Scatter(x=x, y=y, mode='markers', marker=dict(color='white', size=3,
opacity=0.3))],
show_link=False)
print(plot_url)