gpt4 book ai didi

python-3.x - 如何根据 Python 中的日期列绘制分类变量

转载 作者:行者123 更新时间:2023-12-03 23:52:09 25 4
gpt4 key购买 nike

我有看起来像这样的数据

Date         Fruit
2017-01-01 Orange
2017-01-01 Apple
2017-01-08 Orange
2017-01-09 Orange
2017-01-09 Apple

我想在一个图中按日期绘制橙子数量、苹果数量。
我该怎么做?

我按日期将它们分组,然后我看到了结果。
df.groupby(['Date','Fruit']).size()
Date         Fruit
2017-01-01 Orange 1
Apple 1
2017-01-08 Orange 1
2017-01-09 Orange 1
Apple 1

我试过这个,但它给出了一个有两个类别但不针对日期的条形图。
sns.catplot(x="Fruit", hue="Fruit", kind="count",
palette="pastel", edgecolor=".6",
data=df);

如何绘制 x 轴上的日期和每个日期的苹果数量和橙子数量的图表?

最佳答案

构建数据集:

df = pd.DataFrame(columns=["Date", "Fruit"], data=[['2017-01-01','Orange'], ['2017-01-01','Orange'], ['2017-01-01','Apple'], ['2017-01-08','Orange'], ['2017-01-09','Orange'], ['2017-01-09','Apple']])

The data looks like this

通过使用 unstack 和 group by 可以绘制条形图:
(df
.groupby(['Date', 'Fruit'])
.size()
.unstack()
.plot.bar()
)

Here is the plot by date

关于python-3.x - 如何根据 Python 中的日期列绘制分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56050037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com