Colab中的互动图

时间:2018-07-01 02:28:25

标签: python graph mouseevent interactive

有人知道是否有一种方法可以制作图形以使坐标轴上的坐标轴上显示轴值吗?

我发现了一些类似的答案

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中工作

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

我知道了。

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)