下面是创建交互的示例iplot()
在情节和cufflinks()
在 Google Colab 笔记本上。答案中使用的功能和建议 [1 https://stackoverflow.com/questions/47230817/plotly-notebook-mode-with-google-colaboratory, 2]
https://colab.research.google.com/drive/14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f
关键似乎是包括configure_plotly_browser_state()
在进行绘图的单元格中。
下面的代码应该可以工作:
导入库
import datetime
from datetime import date
import pandas as pd
import numpy as np
from plotly import __version__
%matplotlib inline
import plotly.offline as pyo
import plotly.graph_objs as go
from plotly.offline import iplot
import cufflinks as cf
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
cf.go_offline()
将笔记本设置为 false
init_notebook_mode(connected=False)
为 Colab 创建函数复制自: [1 https://stackoverflow.com/questions/47230817/plotly-notebook-mode-with-google-colaboratory, 2] https://colab.research.google.com/drive/14oudHx5e5r7hm1QcbZ24FVHXgVPD0k8f
def configure_plotly_browser_state():
import IPython
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
<script>
requirejs.config({
paths: {
base: '/static/base',
plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',
},
});
</script>
'''))
注意:使用plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext'
确保使用最新版本的 Plotly。还可以通过使用例如来指定plotly的版本plotly: 'https://cdn.plot.ly/plotly-1.5.1.min.js?noext'
.
创建示例数据框
数据来源:国家气象局提供的佐治亚州桃树市的年度降雨量数据[3] https://www.weather.gov/ffc/rainfall_scorecard.
df = pd.DataFrame({
'month': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
'Year_2018': [3.26, 6.11, 4.86, 6.53, 4.45, 3.86, 8.04, 7.59, 1.48, 4.75, 7.27, 11.83],
'Year_1996': [8.26, 3.82, 6.42, 2.91, 2.12, 1.70, 2.14, 4.66, 4.32, 0.89, 3.22, 4.14]
}
)
df
创建交互式 iplot
configure_plotly_browser_state()
df.iplot(kind='line',x='month',y=['Year_2018', 'Year_1996'], color=['white', 'gold'],
theme='solar', mode='markers+lines',title='Annual Rainfall in the city Peachtree City, GA')
Output: