0

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

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

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

这可能与 Matplotlib 有关吗?

提前非常感谢大家。

4

2 回答 2

0

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

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
于 2020-08-10T18:39:36.463 回答
0

Welcome to stackoverflow my friend. As an advice, it would be better you show a piece of your data frame. I created a dummy dataframe like this;

enter image description here

First, you need to turn your year variable to categorical(just an advice)

df["Year"] = df["Year"].astype('category')

Then I used this piece of code

ax = df.plot(x="Year", y="Var1", kind="bar")
df.plot(x="Year", y="Var2", kind="bar", ax=ax, color="C2")

the output is like this

enter image description here

于 2020-08-10T19:04:30.993 回答