簡體   English   中英

用 Matplotlib 在 Python 中繪制 dataframe - 水平條形圖

[英]Plotting dataframe in Python with Matplotlib - Horizontal Bar Chart

這是我在論壇上的第一個問題。

我正在使用 Pandas 來讀取 a.dta 數據庫。 在這個數據庫中,我有不同年份進行的一項調查的答案。 在這種情況下,2011-2012-2013-2014。

我想要做的是一個帶有兩個變量交叉的水平條形圖,但是每年的結果都在同一個圖表中看到,而不是為進行調查的每一年制作圖表。

這可能與 Matplotlib 有關嗎?

提前非常感謝大家。

您可以使用此代碼水平 plot 您的圖表

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

歡迎來到stackoverflow我的朋友。 作為建議,最好顯示一個數據框。 我像這樣創建了一個虛擬 dataframe;

在此處輸入圖像描述

首先,您需要將您的年份變量轉換為分類(只是一個建議)

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")

output 是這樣的

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM