繁体   English   中英

python中的简单条形图

[英]Simple Bar Plot in python

我正在尝试为keyword vs frequency列表绘制一个简单的bar plot 由于数据没有header我无法使用PandasSeabron.

输入

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

代码:

from matplotlib import pyplot as plt
from matplotlib import*
import numpy as np 

x,y = np.genfromtxt('theri_split_keyword.csv', delimiter = ',', unpack=True, comments=None, usecols=(0,1))

plt.bar(x,y)

plt.title('Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')

plt.show()

我想要绘制的只是一个条形图, x axis为关键字, y axis为频率。 绘制此图的任何简单方法都将是巨大的帮助。

我得到的输出如下,这绝对不是我要找的。 在此处输入图片说明

下面的解决方案似乎很有用,但我的列表中有太多关键字,我正在寻找一个选择,比如我是否只能用相应的关键字绘制前 10-20 个关键字,以便条形图看起来更好。

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

在此处输入图片说明

不回答你的问题,但熊猫不需要数据有标题。 如果您从文件中读取数据,只需选择 header=None(更多信息在这里)。

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')

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

df = pd.DataFrame({'word':['w1','w2','w3'],'freq':[1,2,3})
df.plot.bar()
    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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM