绘制直方图matplotlib,标签位于x轴而不是conn

2024-04-28 11:04:09 发布

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

我想用python中的value_counts()或类似的工具绘制一个直方图。我的数据看起来像:

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

您可以使用任何可重复的代码,如:

pd.DataFrame({'Family':['Lannister', 'Stark'], 'Battles':[6, 8]})

我在用

plt.hist(battles.attacker_1.value_counts())

histogram

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


Tags: 工具数据value绘制直方图次数counts姓氏
3条回答

明白了。

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

你可以看看pandasplot

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

enter image description here

对于vanilla 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()

结果是:

histogram plot

相关问题 更多 >