[英]How do I combine subplots in matplotlib?
我得到一個 mongodb 查詢(不確定該位是否相關)並嘗試 plot 基於其中一列的值的堆疊直方圖。
cursor = db.gadgets.find()
df = pd.DataFrame(cursor)
df['created'].hist(by=df['gadgetTypeId'], sharex=True, sharey=True, figsize=(16,10), legend=True)
到目前為止一切順利,但它創建了一堆子圖。 我想要一個堆疊的子圖。
試圖使用matplotlib.pyplot.hist()
得到這個,但找不到如何使用by
參數。
用以下玩具 dataframe:
import pandas as pd
df = pd.DataFrame(
{
"gadgetTypeId": [1, 2, 3, 3, 1, 2, 2, 1, 2, 1],
"created": [2017, 2018, 2018, 2019, 2017, 2018, 2017, 2017, 2019, 2019],
}
)
這是一種方法:
import matplotlib.pyplot as plt
plt.hist(
x=[df.loc[df["gadgetTypeId"] == i, "created"] for i in df["gadgetTypeId"].unique()],
stacked=True,
color=["r", "g", "b"],
label=df["gadgetTypeId"].unique(),
)
plt.xticks(ticks=df["created"])
plt.yticks(ticks=range(df["created"].value_counts().max() + 1))
plt.legend()
哪個輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.