【问题标题】:Matplotlib legend with line breaks带有换行符的 Matplotlib 图例
【发布时间】:2019-08-31 01:19:57
【问题描述】:

我正在尝试将我的回归系数作为 LaTeX 公式添加到具有多行的子图的图例中:

fig, ((plt1, plt2, plt3), (plt4, plt5, plt6)) = plt.subplots(2, 3, figsize=(22,10), sharex='col', sharey='row')

plot1, = plt1.plot('Normalized Times','Mean', linestyle='None', marker='o', color='#6E9EAF', markersize=marksize, data=Phase1_Temp)

plot1_R, = plt1.plot(Xdata_Phase1_Temp, Y_Phase1_Temp_Pred, linewidth=width_line, color=Orange)

plt1.legend([plot1_R], ["$f(x) = {m}*x +{b}$".format(m=np.round(A[1],2), b=np.round(A[0],2)) "\n" "$R2 = {r}$".format(r=np.round(A[2],2))])

当我运行文件时,当我为一个句柄调用第二个标签时,语法无效:

  "\n" "$R2 = {r}$".format(r=np.round(A[2],2))])
       ^
SyntaxError: invalid syntax

有人知道如何解决这个问题吗?

【问题讨论】:

  • "\n" 是干什么用的?

标签: python matplotlib legend subplot


【解决方案1】:

考虑使用单个字符串进行格式化

import matplotlib.pyplot as plt

A = [5,4,3]

fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(22,10), sharex='col', sharey='row')

plot1, = ax1.plot([0,1], linestyle='None', marker='o', color='#6E9EAF', markersize=5)

plot1_R, = ax1.plot([0,1], linewidth=2, color="orange")

ax1.legend([plot1_R], 
           ["$f(x) = {m}*x +{b}$\n$R2 = {r}$".format(m=np.round(A[1],2), 
                                                     b=np.round(A[0],2), r=np.round(A[2],2))])

plt.show()

另外,f-strings 在这里可能会派上用场,因为在格式化级别执行舍入。

ax1.legend([plot1_R], [f"$f(x) = {A[1]:.2f}*x +{A[0]:.2f}$\n$R2 = {A[2]:.2f}$"])

【讨论】:

    【解决方案2】:

    在python中,你可以像这样连接字符串:

    "hello " "world"
    

    并产生"hello world"。但是如果你这样做,那就是语法错误:

    "{} ".format("hello") "world"
    

    因此,如果您想从format() 的输出中连接,请使用+

    "{} ".format("hello") + "world"
    

    在你的情况下(添加换行符以提高可读性):

    plt1.legend([plot1_R], [
        "$f(x) = {m}*x +{b}$".format(m=np.round(A[1],2), b=np.round(A[0],2))
        + "\n"
        + "$R2 = {r}$".format(r=np.round(A[2],2))
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多