繁体   English   中英

无法在绘图中显示多线方程注释(Python)

[英]Unable to display a multi-line equation annotation in plotly (Python)

我正在尝试创建一个由拟合方程和最佳参数组成的注释。 我使用了一个字符串标签,该标签也用于使用matplotlib生成类似的输出。 标签有数学符号/符号。

一个最小的例子:

import plotly.graph_objects as go

# make up some points
xpts = [0, 1, 2, 3, 4]
ypts = [0, 2, 4, 6, 8]

# the annotation to display
func_label = "".join(["$f(x) = mx + b$\n",
                      f"$m = 2.0$ \n",
                      f"$b = 0.0$\n",
                      f"$R^2 = 0.99$\n",
                      f"$RMSE = 0.01$",])

fig = go.Figure(
    data=[go.Scatter(x=xpts,
                     y=ypts,
                     mode='markers',
                     name="Data"
                     ),
          ],
    layout=go.Layout(title="Plot Title",
                     xaxis_title="X-axis",
                     yaxis_title="Y-axis")
)

# add the annotation
fig.add_annotation(x=0.25, y=6, text="<br>".join(func_label.split('\n')), showarrow=False)

fig.show(renderer="browser")

生成的绘图输出仅显示注释的第一行: 仅使用 1 行注释进行绘图!

似乎$可能会导致问题,因为当我删除它们时,它会打印所有行。 有没有办法在保留数学渲染的同时做到这一点?

好的,

我似乎找到了解决办法。 mathjax中,换行符由\\表示(例如,请参见此处https://stackoverflow.com/a/32507429/13752965 )。 为了在 Python + plotly 中使用它,我必须添加一个额外的转义字符\ (尽管我还没有完全弄清楚为什么)。

所以使用

func_label = '$f(x) = mx + b \\\ m = 2.0 \\\ b = 0.0 \\\ R^2 = 0.99 \\\ RMSE = 0.01$'

我可以使用我想要的公式格式获得多行注释。 在此处输入图像描述

我仍在修改是否可以在问题中使用splitjoin方法,但这是一个合理的选择。

在这种情况下,$ 表示开始和结束,因此开始和结束字符串将解决问题。 可以在创建字符串时使用换行符来做到这一点,尽管由于时间不够,我还没有验证这一点。

# the annotation to display
func_label = f"<br>".join([f"$f(x) = mx + b",
                      f"m = 2.0 ",
                      f"b = 0.0",
                      f"R^2 = 0.99",
                      f"RMSE = 0.01$",])

fig = go.Figure(
    data=[go.Scatter(x=xpts,
                     y=ypts,
                     mode='markers',
                     name="Data"
                     ),
          ],
    layout=go.Layout(title="Plot Title",
                     xaxis_title="X-axis",
                     yaxis_title="Y-axis")
)

# add the annotation
fig.add_annotation(x=0.25, y=6, text=func_label, showarrow=False)

fig.show(renderer="browser") 
#fig.show()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM