gpt4 book ai didi

python - Plotly:如何在多行上绘制分组结果?

转载 作者:行者123 更新时间:2023-12-01 07:24:52 25 4
gpt4 key购买 nike

我正在尝试根据“Plotly”中按类别和日期划分的 ID 计数来创建多折线图我的日期包含三列“日期”,“类别”,“ID”

我现在使用此代码绘制了一条线

b=mdata.groupby(['Date']).count()['ID ']
b=b.sort_index(ascending=True)


xScale = b.index
yScale = b.values
trace =go.Scatter(
x = xScale,
y = yScale,
marker=dict(
color='Red')

)
data2 = [trace]
graphJSON2 = json.dumps(data2, cls=plotly.utils.PlotlyJSONEncoder)

输出图表应在 X 轴上包含日期,在 Y 轴上包含 ID 计数以及基于类别的多行

最佳答案

据我所知,您将不得不使用类似 pandas.DataFrame.pivot 的方法在这里获取您正在寻找的数据结构:

pd.pivot_table(df, values='ID', index=['Date'],columns='Category', aggfunc=np.sum)

下面是一个完整的方法,应使用以下示例数据框来适合您的数据集的描述:

数据:

         Date  ID Category
0 2013-01-02 1 A
1 2013-01-02 3 B
2 2013-01-03 1 C
3 2013-01-03 2 B
4 2013-01-03 1 B
5 2013-01-03 3 A
6 2013-01-03 3 A
7 2013-01-03 4 A
8 2013-01-04 4 B
9 2013-01-04 4 C
10 2013-01-05 1 B
11 2013-01-06 2 A

plotly :

enter image description here

代码:

import plotly.graph_objs as go
import pandas as pd
import numpy as np

# sample dataframe to match OPs structure
df = pd.DataFrame({'Date' : [pd.Timestamp('20130102'), pd.Timestamp('20130102'),
pd.Timestamp('20130103'), pd.Timestamp('20130103'),
pd.Timestamp('20130103'), pd.Timestamp('20130103'),
pd.Timestamp('20130103'), pd.Timestamp('20130103'),
pd.Timestamp('20130104'), pd.Timestamp('20130104'),
pd.Timestamp('20130105'),pd.Timestamp('20130106')],
'ID' : [1, 3, 1, 2, 1 , 3,3,4,4,4,1,2],
'Category' : pd.Categorical(["A","B","C","B","B","A",
"A","A","B","C","B","A" ])})
# data munging to get OPs desired plot
df = pd.pivot_table(df, values='ID', index=['Date'],columns='Category', aggfunc=np.sum)

# ploty
fig = go.Figure()
for col in df.columns:
fig.add_trace(go.Scatter(x=df.index, y=df[col].values,
name = col,
mode = 'markers+lines',
line=dict(shape='linear'),
connectgaps=True
)
)
fig.show()

关于python - Plotly:如何在多行上绘制分组结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57502469/

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