pandas 在 x 轴上使用标签而不是计数绘制直方图 matplotlib

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48799185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:11:05  来源:igfitidea点击:

plot histogram matplotlib with labels on x axis instead of count

pythonpandasmatplotlib

提问by Matt W.

I'm looking to plot a histogram using value_counts()or some equivalent, in python. My data looks like:

我希望value_counts()在 python 中使用或某种等效方法绘制直方图。我的数据看起来像:

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

histogram

直方图

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. 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.

我希望 x 轴显示姓氏,而不是战斗次数,并且我希望将战斗次数作为直方图。我尝试只使用一系列姓氏(兰尼斯特重复 8 次),而不是使用,value_counts()并认为这可能有用,但我不知道如何才能做到这一点。

回答by Matt W.

Figured it out.

弄清楚了。

battles.attacker_1.value_counts().plot(kind = 'bar')

回答by jrd1

For a vanilla matplotlibsolution, use xticklabelswith xticks:

对于香草matplotlib的解决方案,使用xticklabelsxticks

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:

其中产生:

histogram plot

直方图

回答by YOBEN_S

You may look at pandasplot

你可以看看 pandasplot

df.set_index('Family').Battles.plot(kind='bar')

enter image description here

在此处输入图片说明