【问题标题】:Adding the name of the corresponding file to the plot in matplotlib [duplicate]将相应文件的名称添加到matplotlib中的绘图中[重复]
【发布时间】:2018-08-30 06:00:19
【问题描述】:

我是 Python 新手(以及编程方面的新手),我正在尝试构建用于 .csv 数据分析的程序。
我有多个 .csv 文件,我为每个文件构建了一个情节。
如何将相应文件的名称添加到情节的标题中? 谢谢!

下面是对应部分的代码:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import glob

for fName in glob.glob('*.csv'): 
    df, loops = openF(fName)
    fig, ax = plt.subplots(1, 1)

    for i in range(loops):
        df.loc[df['loop']==i+1][['freq','phase']].plot(x='freq', y='phase', logx=True, ax=ax)
    ax.set_title('Phase/Freq'.format(fName))
    ax.set_xlabel('Frequency, [Hz]')
    ax.set_ylabel('Phase, [rad]')



plt.show()

【问题讨论】:

  • 您在.format 中忘记了{}。但是你可以写ax.set_title('Phase/Freq %s'fName),或者干脆写ax.set_title('Phase/Freq ' + fName)
  • 谢谢,David Leon,现在可以使用了!!! :)

标签: python pandas matplotlib


【解决方案1】:

你说得差不多了。

为了使format 方法起作用,您必须向它显示 fName 的放置位置。 所以你必须改变

ax.set_title('Phase/Freq'.format(fName))

ax.set_title('Phase/Freq {}'.format(fName)).

这里是关于 format 的完整文档: https://docs.python.org/3.4/library/string.html#format-specification-mini-language

此外,如果您对使用 python3.6 感到满意,您可以使用 f-string https://www.python.org/dev/peps/pep-0498/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多