[英]plot histogram matplotlib with labels on x axis instead of count
I'm looking to plot a histogram using value_counts()
or some equivalent, in python. 我想在python中使用value_counts()
或等效的图表来绘制直方图。 My data looks like: 我的数据如下:
Lannister 8
Stark 8
Greyjoy 7
Baratheon 6
Frey 2
Bolton 2
Bracken 1
Brave Companions 1
Darry 1
Brotherhood without Banners 1
Free folk 1
Name: attacker_1, dtype: int64
You could use any reproducible code like: 您可以使用任何可复制的代码,例如:
pd.DataFrame({'Family':['Lannister', 'Stark'], 'Battles':[6, 8]})
I'm using 我正在使用
plt.hist(battles.attacker_1.value_counts())
I would like the x axis to show the family names, instead of the number of battles, and I would like the number of battles to be the histogram piece. 我希望x轴显示姓氏,而不是战斗次数,并且我希望战斗次数是直方图。 I tried using just a series of the family names (with Lannister repeating 8 times) instead of using value_counts()
and thought that might work, but I'm not sure how else to do this. 我尝试仅使用一系列姓氏(Lannister重复了8次),而不是使用value_counts()
并认为这可能有效,但是我不确定其他方法。
弄清楚了。
battles.attacker_1.value_counts().plot(kind = 'bar')
For a vanilla matplotlib solution, use xticklabels
with xticks
: 对于香草matplotlib解决方案, xticklabels
与xticks
xticklabels
使用:
import random
import matplotlib.pyplot as plt
NUM_FAMILIES = 10
# set the random seed (for reproducibility)
random.seed(42)
# setup the plot
fig, ax = plt.subplots()
# generate some random data
x = [random.randint(0, 5) for x in range(NUM_FAMILIES)]
# create the histogram
ax.hist(x, align='left') # `align='left'` is used to center the labels
# now, define the ticks (i.e. locations where the labels will be plotted)
xticks = [i for i in range(NUM_FAMILIES)]
# also define the labels we'll use (note this MUST have the same size as `xticks`!)
xtick_labels = ['Family-%d' % (f+1) for f in range(NUM_FAMILIES)]
# add the ticks and labels to the plot
ax.set_xticks(xticks)
ax.set_xticklabels(xtick_labels)
plt.show()
Which yields: 产生:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.