【问题标题】:Plotting dataframe in Python with Matplotlib - Horizontal Bar Chart使用 Matplotlib 在 Python 中绘制数据框 - 水平条形图
【发布时间】:2020-11-30 09:38:30
【问题描述】:

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

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

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

这可能与 Matplotlib 相关吗?

提前非常感谢大家。

【问题讨论】:

  • 欢迎来到 Stack Overflow!请使用tour 并通读help center,尤其是how to ask。你最好的选择是做你的研究,搜索关于 SO 的相关主题,然后试一试。在进行更多研究和搜索后,发布您的尝试Minimal, Complete, and Verifiable example,并具体说明您遇到的问题,这可以帮助您获得更好的答案。

标签: python pandas matplotlib plot dta


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

欢迎来到 stackoverflow 我的朋友。作为建议,最好显示一个数据框。我创建了一个这样的虚拟数据框;

首先,您需要将年份变量转换为分类变量(只是一个建议)

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

然后我就用了这段代码

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

输出是这样的

【讨论】:

  • 您好 sametsokel,感谢您对论坛的欢迎。我刚刚发布了一个答案,详细说明了我想要做什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多