Colab 中的交互式图形



>有谁知道是否有办法制作一个图表,以便在 Colab 中悬停时显示轴值?

我找到了几个答案,大致如下:

import matplotlib.pylab as plt
import numpy as np
f,a = plt.subplots()
x = [0,1,2,3]
y = [5,6,7,8]
a.plot(x,y)
pos = []
def onclick(event):
pos.append([event.xdata,event.ydata])
f.canvas.mpl_connect("motion_notify_event", 'hover')
plt.show()

但不幸的是,它们似乎在 Colab 中不起作用

尝试以下代码并根据您的函数对其进行修改。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML
# First set up the figure, the axis, and the plot element we want to animate
fig, ax = plt.subplots()
plt.close()

ax.set_xlim(( 0, 2))
ax.set_ylim((-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return (line,)
# animation function. This is called sequentially  
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return (line,)

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=100, blit=True)
# Note: below is the part which makes it work on Colab
rc('animation', html='jshtml')
anim

Nm,我想通了。

import IPython
import numpy as np
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
def configure_plotly_browser_state():
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>
'''))
configure_plotly_browser_state()
init_notebook_mode(connected=False)
trace1 = go.Scatter(
x= x_data,
y= y_data,
marker={'color': 'blue', 'symbol': 42, 'size': "10"},
mode='lines+markers+text',
name = 'Data1',
hoverinfo = 'x+y'
)
trace2 = go.Scatter(
x= x_data2,
y= y_data2,
marker={'color': 'red', 'symbol': 42, 'size': "10"},
mode='lines+markers+text',
name='Data2',
hoverinfo = 'x+y'
)
layout = go.Layout(
autosize=True,
title='Interactive chart',
xaxis=dict(
title='Title',
titlefont=dict(
family='Courier New, monospace',
size=18,
color='#7f7f7f'
)
),
yaxis=dict(
title='Title',
titlefont=dict(
family='Courier New, monospace',
size=18,
color='#7f7f7f'
)
)
)
fig = go.Figure(data=[trace1, trace2], layout = layout)
iplot(fig)

最新更新