【问题标题】:Printing a .txt file in a graph using Matplotlib使用 Matplotlib 在图中打印 .txt 文件
【发布时间】:2020-03-24 15:47:04
【问题描述】:

我正在通过一个程序接收用户的 .txt 文件,该文件一次使用 3 行:第一行是 X 坐标,第二行是 y 坐标。第三行是样式。 (用户可以根据需要输入任意数量的 3 行的不同部分。程序将从lines[0]-line[2] 开始处理并打印相应的图形,然后lines[3]-line[5] 并执行相同的操作。一直到最后。 一张图的例子:

2 4 6

1 2 3

--r

我已经打好了基础。但是,当我尝试在 plt.plot() 中实现第三行时,程序由于无法识别的错误而崩溃:

'Unrecognized character %c in format string' % c) (底部完整回溯)

ValueError:无法识别的字符 在格式字符串中。 请参阅下面的代码:

import matplotlib.pyplot as plt

with open("testfile.txt") as f:
    lines = list(f)
    x_components = list(map(int, lines[0].split()))
    y_components = list(map(int, lines[1].split()))
    style = lines[2]
    line_to_string = "".join(map(str, style))
    plt.plot(x_components, y_components, line_to_string)

非常感谢任何帮助。

追溯:

Traceback (most recent call last):
  Traceback (most recent call last):
  File "plots.py", line 11, in <module>
    plt.plot(x_components, y_components, line_to_string)
  File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py", line 2795, in plot
    is not None else {}), **kwargs)
  File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_axes.py", line 1666, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 225, in __call__
    yield from self._plot_args(this, kwargs)
  File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 366, in _plot_args
    linestyle, marker, color = _process_plot_format(tup[-1])
  File "/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 106, in _process_plot_format
    'Unrecognized character %c in format string' % c)
ValueError: Unrecognized character 
 in format string
>

.txt 文件的屏幕截图如下:

【问题讨论】:

  • 包含错误会帮助那些试图帮助你的人!
  • 谢谢。查看修改
  • 请发布完整回溯
  • 实际上,您的代码对我来说运行良好,但我确保输入文件的数据之间没有行。如果有的话,我会遇到类似的错误。检查您的输入数据...
  • @daveg 看看截图。你的输入是一样的吗?

标签: python python-3.x matplotlib graph


【解决方案1】:

尝试从这一行调试它 - style = lines[2]line_to_string 可以包含'\n' 什么的

【讨论】:

    【解决方案2】:

    你应该从格式字符串的末尾去掉换行符:

    with open("testfile.txt") as f:
        lines = f.readlines()
        x_components = list(map(int, lines[0].split()))
        y_components = list(map(int, lines[1].split()))
        style = lines[2].strip()
        line_to_string = "".join(map(str, style))
        plt.plot(x_components, y_components, line_to_string)
    

    顺便说一句,如果您不检查格式字符串是否有效,该方法很脆弱。

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多