基于列的周线图的数据帧线图

2024-09-20 22:59:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,其中包含类型(色调列)的年、月和周计数:

Type    Year    Month      Week Count
Chat    2020    December    52  3
Chat    2020    December    53  3
Clinic  2020    December    52  433
Clinic  2020    December    53  245
Video   2020    December    52  115
Video   2020    December    53  69
Chat    2021    January     1   3
Chat    2021    January     2   7
Clinic  2021    January     1   500
Clinic  2021    January     2   200
Video   2021    January     1   50
Video   2021    January     2   20

我必须为每种类型(数据框列名)绘制一个线图,y轴为计数,x轴为12月到1月,还有周

地块应为2020年12月至2021年1月

我试图有计划地去做,但没能做到

我的代码:

fig = go.Figure()
        
        for appType, sub_data in temp.groupby('Appointment Type'):
            print(appType)
            tempX = sub_data['Month'].tolist()
            tempX.sort(reverse=True)
            tempY = sub_data['Count'].tolist()
            tempY.sort(reverse=True)
            
            fig.add_scatter(x=tempX, y=tempY, name=appType, mode='lines')
        
        fig.update_layout(
            title='Appointment Type-Overall - no.of.app={}|no.of.doctors={}'.format(sampleSize,sampleDoc),
            xaxis_title='Month of the Year',
            yaxis_title='Count',
            xaxis=dict(tickformat="%m")
            )

如何实现这样的用例


Tags: ofdatatitlevideotypecountchatfig
1条回答
网友
1楼 · 发布于 2024-09-20 22:59:27

将数据读入数据帧后,首先只筛选出首选时间段内所需的行:

import pandas as pd

df = pd.read_csv('path_to_your_csv')
df = df[((df['Month'] == 'December') & (df['Year'] == 2020)) | ((df['Month'] == 'January') & (df['Year'] == 2021))]

然后在pandas中使用groupby()plot()以获得所需的结果:

import matplotlib.pyplot as plt

df.groupby(['Year','Week','Type']).Count.sum().unstack('Type').plot()
plt.ylabel('Count')
plt.show()

样本输出:

enter image description here

相关问题 更多 >

    热门问题