我试图发送到matplotlib的数据有什么问题?

2024-04-26 13:12:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下脚本:

import pandas
from collections import Counter
import matplotlib.pyplot as plt

while True:
    data = [int(x) for x in raw_input("Enter the list containing the data: ").split()]
    letter_counts = Counter(data)
    df = pandas.DataFrame.from_dict(letter_counts, orient="index")
    df.plot(kind="bar")
    plt.show()

例如,当我键入或复制粘贴一个序列或数字时

 1 4 5 6 3

这个脚本工作得很好,并向我显示了直方图。但是,当我粘贴输出中的数字时,我会从另一个终端窗口中获取,例如:

  13 13 16 16 16 16 9 9 9 9 9 15 15 15 15 20 20 20 20 20 22 22 22 22 13
  13 13 13 12 12 12 12 12 16 16 16 16 15 15 15 15 15 15 15 15 15 15 15
  15 15 22 22 22 22 22 15 15 15 15 13 13 13 13 13 18 18 18 18 10 10 10
  10 12 12 12 12 12 10 10 10 10 20 20 20 20 20 15 15 15 15 15 15 15 15
  17 17 17 17 17 13

我第一次输入数据时,它工作得很好;但是,当我在时间输入数据时,它什么都不做,然后我必须再次按enter键。它向我显示了绘图,但当我关闭它时,它会显示以下错误:

> Enter the list containing the data: Traceback (most recent call last):
> File "make_histo.py", line 9, in <module>
>     df.plot(kind="bar")   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 2627, in __call__
>     sort_columns=sort_columns, **kwds)   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 1869, in plot_frame
>     **kwds)   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 1694, in _plot
>     plot_obj.generate()   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 243, in generate
>     self._compute_plot_data()   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 352, in _compute_plot_data
>     'plot'.format(numeric_data.__class__.__name__)) 
TypeError: Empty 'DataFrame': no numeric data to plot

我做错什么了?你知道吗


Tags: theinpycorepandasdataplotlib
1条回答
网友
1楼 · 发布于 2024-04-26 13:12:15

我不太明白你描述的行为:当我复制粘贴你问题中的数字块时,我得到嵌入的换行符,这会导致raw\u input()被多次调用。你知道吗

解决这个问题的一个可能的方法是让程序将空行视为输入的结尾:以下非常简单的代码在我的系统(Windows,Python 2.7)上接受数字块OK的复制粘贴:

while True:
    print ("Enter the list containing the data: ")
    lines = []
    while True:
        line = raw_input()
        if (line):
            lines.append(line.lstrip().strip())
        else:
            break
    data = []
    for line in lines:
        for x in line.split():
            data.append(int(x))
    print data 

希望这能有所帮助。你知道吗

相关问题 更多 >