【问题标题】:Formatting of title in MatplotlibMatplotlib 中的标题格式
【发布时间】:2013-09-09 03:34:51
【问题描述】:

我有以下 python 代码:

def plot_only_rel():
    filenames = find_csv_filenames(path)
    for name in filenames:
        sep_names = name.split('_')
        Name = 'Name='+sep_names[0]
        Test = 'Test='+sep_names[2]
        Date = 'Date='+str(sep_names[5])+' '+str(sep_names[4])+' '+str(sep_names[3])
    plt.figure()
    plt.plot(atb_mat_2)
    plt.title((Name, Test, Date))

但是,当我在我的图形上打印标题时,它会以格式显示

(u'Name=X', u'Test=Ground', 'Date = 8 3 2012')

我有几个问题: 为什么我得到'u'?我如何摆脱它以及括号和引号? 当我使用字幕时也会发生这种情况。

感谢您的帮助。

【问题讨论】:

    标签: python matplotlib title


    【解决方案1】:

    plt.title 接收一个字符串作为它的参数,并且你传入了一个元组(Name, Test, Date)。由于它需要一个字符串,因此它尝试使用元组的 __str__ 方法将其转换为字符串,该方法为您提供了输出。您可能想要执行以下操作:

    plat.title('{0} {1}, {2}'.format(Name, Test, Date))
    

    【讨论】:

      【解决方案2】:

      怎么样:

      plt.title(', '.join(Name,Test,Date))
      

      由于您将标题作为数组提供,因此它显示了数组的表示形式(实际上是元组)。 u 告诉您它是一个 unicode 字符串。

      您还可以使用 format 来更好地指定格式:

      plt.title('{0}, {1}, {2}'.format(Name, Test, Date))
      

      【讨论】:

        【解决方案3】:

        在 Python > 3.6 中,您甚至可以使用 f-string 来简化格式化:

        plt.title(f'{Name}, {Test}, {Date}')
        

        【讨论】:

          【解决方案4】:

          我想补充一下@Gustave Coste 的回答:您也可以直接在 f-strings 中使用列表

          s="Santa_Claus_24_12_2021".split("_")
          print(f'Name={s[0]}, Test={s[1]}, Date={s[2]} {s[3]} {s[4]}')
          

          结果:Name=Santa, Test=Claus, Date=24 12 2021。或者对于您的情况:

          plt.title(f'Name={sep_names[0]}, Test={sep_names[2]}, Date={sep_names[5]} {sep_names[4]} {sep_names[3]}')
          

          【讨论】:

            猜你喜欢
            • 2017-06-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-17
            • 1970-01-01
            • 1970-01-01
            • 2019-05-15
            • 1970-01-01
            相关资源
            最近更新 更多