首页 > 解决方案 > 使用 Matplotlib 在 Python 中绘制数据框 - 水平条形图

问题描述

这是我在论坛上的第一个问题。

我正在使用 Pandas 读取 .dta 数据库。在这个数据库中,我有不同年份进行的一项调查的答案。在这种情况下,2011-2012-2013-2014。

我想要做的是一个带有两个变量交叉的水平条形图,但是每年的结果都在同一个图表中看到,而不是为进行调查的每一年制作图表。

这可能与 Matplotlib 有关吗?

提前非常感谢大家。

标签: pythonpandasmatplotlibplotdta

解决方案


您可以使用此代码水平绘制图表

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


plt.rcdefaults()
fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()
Copy to clipboard

推荐阅读