我想使用matplotlib从员工调查中创建条形图。遵循以下问题的指示
How to create a bar chart/histogram with bar per discrete value?
我提出了代码
satisfaction = survey['satisfaction'].value_counts().sort_index()
ax = satisfaction.plot(kind='bar')
fig = ax.get_figure()
fig.autofmt_xdate()
plt.show()
其中印有以下图表
所以,从这里开始。
1 - 如何集中图表?我的意思是,我在左边框和第一列之间有一个很大的空间,在最后一列和右边框之间根本没有边框。我想要两个相同大小的空格。
2 - 如何更改列标签?第1列的“1”实际上意味着“非常满意”,“2”意味着“满意”等等。我想用词义来代替数值。
3 - 如何放置图表标题和x和y轴标签。
答案 0 :(得分:1)
ax.set_xlim(left=..., right=...)
ax.set_xlabel(...)
和ax.set_ylabel(...)
请注意,在大多数基本的matplotlib教程中都演示了1和3。
这是一个很好的:http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut2.html
对于数字2,它很简单:
import numpy as np
import pandas
import matplotlib.pyplot as plt
datamap = {
1: 'real bad',
2: 'bad',
3: 'meh',
4: 'good',
5: 'way good'
}
df = pandas.DataFrame(data=np.random.choice(range(1,6), size=37), columns=['score'])
df['rating'] = df.score.map(datamap.get)
fig, ax = plt.subplots()
df.rating.value_counts().plot(kind='bar', ax=ax)
## alternatively:
# df.groupby(by='rating').count().plot(kind='bar', ax=ax)
fig.tight_layout()