[英]Simple Bar Plot in python
我正在尝试为keyword vs frequency
列表绘制一个简单的bar plot
。 由于数据没有header
我无法使用Pandas
或Seabron.
输入
#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.