在 Jupyter Notebook 中并排绘制和降价

问题描述 投票:0回答:1

我希望使用

matplotlib
在 Jupyter Notebook(将在 RISE 中使用)中并排显示绘图和 Markdown。我发现以下答案使用
plotly
,

在 Jupyter 中并排显示交互式绘图和 Markdown 文本

并简单地通过添加一些

matplotlib
元素来修改它

from ipywidgets import widgets, Layout
from IPython.display import display, Javascript, Markdown as md
import numpy as np
import matplotlib.pyplot as plt

def func(x, a, b, c, d):
    return a + b*np.exp(c*x + d)

the_x = np.arange(0, 10, 0.5)
the_y = func(the_x, 1, 1, -1, 2)

fig, ax = plt.subplots()
ax.plot(the_x, the_y)

len_x = len(the_x)

mdout = md(f"""There are {len_x} **elements** of both `the_x`, and `the_y`;

Those values are plotted on the diagram on the left""")


box_layout = Layout(display='flex',
                    flex_flow='row',
                    justify_content='space-around',
                    width='auto'
                   )

hbox1 = widgets.Box(children=[fig, widgets.HTML(mdout._repr_markdown_())], layout=box_layout)
display(hbox1)

但是,它不适用于以下错误消息:

TraitError: The 'children' trait of a Box instance contains an Instance of a TypedTuple which expected a Widget, not the Figure <Figure size 640x480 with 1 Axes>.

大约是从底部算起的第二行。

有人可以帮忙吗?

matplotlib jupyter-notebook markdown
1个回答
0
投票

我手中的作品如下:

#based on https://stackoverflow.com/q/78670150/8508004, and adapting to put matplotlib in a widget from https://stackoverflow.com/a/51060721/8508004 (which I think was adapted in some ways from https://github.com/jupyter-widgets/ipywidgets/issues/2821)
from ipywidgets import widgets, Layout
from IPython.display import display, Javascript, Markdown as md
import numpy as np
import matplotlib.pyplot as plt

left_widget = widgets.Output()
def func(x, a, b, c, d):
    return a + b*np.exp(c*x + d)

the_x = np.arange(0, 10, 0.5)
the_y = func(the_x, 1, 1, -1, 2)

with left_widget:
    fig, ax = plt.subplots()
    ax.plot(the_x, the_y)
    plt.show(fig)

len_x = len(the_x)

mdout = md(f"""There are {len_x} **elements** of both `the_x`, and `the_y`;
Those values are plotted on the diagram on the left""")

box_layout = Layout(display='flex',
                    flex_flow='row',
                    justify_content='space-around',
                    width='auto'
                   )

hbox1 = widgets.Box(children=[left_widget, widgets.HTML(mdout._repr_markdown_())], layout=box_layout)
display(hbox1)

唯一真正的变化是将 Matplotlib 绘图对象包装在 ipywidget 的 Output() 小部件的上下文中,该小部件“可以捕获和显示 IPython 生成的 stdout、stderr 和丰富输出”,然后将该小部件用作子项的左侧在 ipywidget 的框中。 (查找与

left_widget
相关的代码,以了解与原始提供的代码的差异。)

相关资源:

© www.soinside.com 2019 - 2024. All rights reserved.