python中的简单条形图

2024-10-02 04:33:21 发布

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

我试图为一个keyword vs frequency列表绘制一个简单的bar plot。 由于数据没有header,我无法使用Pandas或{}

输入

#kyuhyun,1
#therinewyear,4
#lingaa,2
#starts,1
#inox,1
#arrsmultiplex,1
#bollywood,1
#kenya,1
#time,1
#watch,1
#malaysia,3

代码:

^{pr2}$

我只想绘制一个条形图,其中x axis作为关键字,y axis表示频率。任何简单的方法来描绘这一切都将是巨大的帮助。在

我得到的输出如下,这绝对不是我要找的。 enter image description here

下面的解决方案似乎很有魅力,但我有太多的关键字在一个列表中,我正在寻找一个选择,如果我可以只绘制前10-20个关键字与各自的关键字,这样条形图将看起来更好。在

答案中给出的解决方案的输出。在

enter image description here


Tags: 数据pandas列表plot绘制bar关键字解决方案
3条回答

不回答您的问题,但pandas不要求数据具有标题。 若从文件中读取数据,只需选择header=None(more infohere)。在

df = pd.read_csv(myPath, header=None)
df.columns = ('word','freq') # my cystom header
df.set_index('word') # not neccesary but will provide words as ticks on the plot
df.plot(kind='bar')

例如,您还可以将数据作为字典传递

^{pr2}$
    import numpy as np
    import matplotlib.pyplot as plt
    import csv

    x = []
    y = []
    with open('theri_split_keyword.csv', "rb") as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:
            x.append(row[0].lstrip('#'))
            y.append(int(row[1]))

    ind = np.arange(len(x))  # the x locations for the groups
    width = 0.35       # the width of the bars

    fig, ax = plt.subplots()
    plt.bar(ind,y)

    ax.set_ylabel('Y axis')
    ax.set_title('X axis')
    ax.set_xticks(ind + width)
    ax.set_xticklabels(x, rotation='vertical')


    plt.show()

我不熟悉np.genfromtxt,但我怀疑问题是当x应该是数值时,它将x作为字符串数组返回。在

或许可以尝试一下:

tick_marks = np.arange(len(x))
plt.bar(tick_marks, y)
plt.xticks(tick_marks, x, rotation=45)

相关问题 更多 >

    热门问题