[英]How do I combine subplots in matplotlib?
I am getting a mongodb query (not sure whether that bit is relevant) and trying to plot a stacked histogram based the values of one of the columns.我得到一个 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)
So far so good, but it creates a bunch of subplots.到目前为止一切顺利,但它创建了一堆子图。 I want one stacked subplot.我想要一个堆叠的子图。
Tried to get this using matplotlib.pyplot.hist()
, but couldn't find how to use the by
argument.试图使用matplotlib.pyplot.hist()
得到这个,但找不到如何使用by
参数。
With the following toy dataframe:用以下玩具 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],
}
)
Here is one way to do it:这是一种方法:
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()
Which outputs:哪个输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.