Google Colab中的交互式matplotlib图形

2024-04-26 13:44:40 发布

您现在位置:Python中文网/ 问答频道 /正文

通常在jupyter笔记本中,我会使用%matplotlib notebook魔术来显示一个交互式窗口,但是这似乎不适用于google colab。是否有解决方案,或是不可能在google colab中显示交互式窗口?


Tags: matplotlibgoogle魔术笔记本jupyter解决方案colabnotebook
2条回答

下面是在Plotly和Google Colab笔记本上创建交互式iplot()的示例。使用的函数和来自答案的建议 [12]

关键似乎是在进行绘图的单元格中包含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创建函数 抄送自: [12]

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-1.5.1.min.js?noext',
            },
          });
        </script>
        '''))

创建示例数据框

数据来源:美国国家气象局(National Weather Service)提供的佐治亚州桃树市年降雨量数据。

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')
plt.show()

输出: enter image description here

enter image description here

[注:x,y,标题不显示!目前。】

这似乎是一个后端问题。在jupyter笔记本中,列出不同类型后端的命令是:

%matplotlib --list

输出:

Available matplotlib backends: ['tk', 'gtk', 'gtk3', 'wx', 'qt4', 'qt5', 'qt', 'osx', 'nbagg', 'notebook', 'agg', 'svg', 'pdf', 'ps', 'inline', 'ipympl', 'widget']

但是,对于我的系统/设置,只有“笔记本”和其他一个可以工作。在jupyter实验室,对我来说,没有一个后端可以用于交互式图形(甚至是他们推荐的“内联”)。

希望它能减少我进行安装/重新安装的搜索时间和排列:)

相关问题 更多 >