我想用类似于我在下面创建的 df 的数据制作三个不同的图(按位置)。在 x 轴上,我需要 y 轴上的日期和数字。最好是每个日期都有一个条形图的条形图。
是否可以使用例如在几行简单的行中完成它该位置的 groupby 功能?
谢谢!
data = {"location": ["USA", "USA", "USA", "UK", "UK", "UK", "World", "World", "World"], "date": ["21-06-2021", "22-06-2021", "23-06-2021", "21-06-2021", "22-06-2021", "23-06-2021", "21-06-2021", "22-06-2021", "23-06-2021"], "number": [456, 543, 675, 543, 765, 345, 654, 345, 654]}
import pandas as pd
df = pd.DataFrame (data, columns = ['location','date','number'])
df["date"] = pd.to_datetime(df["date"])
df
最佳答案
您不是在这里进行分组,您只想为每个位置设置不同的行。
样本数据
# using data from OP
df = pd.DataFrame (data, columns = ['location','date','number'])
# using .dt.date will remove the time component for nicer x-axis labels
df["date"] = pd.to_datetime(df["date"]).dt.date
线图Plotly
import plotly.express as px
px.line(df, x='date', y="number", color="location")
![enter image description here](https://i.sstatic.net/JRcYm.png)
Seaborn
import seaborn as sns
p = sns.catplot(data=df, x='date', y="number", hue='location', kind='point', height=4, aspect=1.5)
![enter image description here](https://i.sstatic.net/zi73E.png)
Pandas
如果你更喜欢只使用 Pandas ,你可以关注这个 answer
pandas.DataFrame.plot
pv = df.pivot(index="date", columns='location', values='number')
ax = pv.plot(figsize=(16, 6))
![enter image description here](https://i.sstatic.net/MkNmt.png)
我的建议是尝试使用 plotly。你可以有很好的交互式绘图,语法也很简单。
条形图
情节
px.bar(df, x='date', y="number", color="location", barmode='group')
![enter image description here](https://i.sstatic.net/S08JZ.png)
海伯恩
p = sns.catplot(data=df, x='date', y="number", hue='location', kind='bar', height=4, aspect=1.5)
![enter image description here](https://i.sstatic.net/VzCLx.png)
Pandas
ax = pv.plot(kind='bar', figsize=(8, 5), rot=0)
![enter image description here](https://i.sstatic.net/jiQyU.png)
关于python - 在python中用pandas groupby绘图,多幅图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68180115/