如何使用此数据框创建简单的交互式绘图

2024-06-07 16:49:23 发布

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

我正在尝试使用我在datacamp上看到的一个示例制作一个交互式图形,但我不知道如何使用不同类型的数据帧。这是我的数据帧(我通过添加来自其他dfs的列来创建它):

enter image description here

如何遍历具有不同名称的列?以及如何选择日期列

这是我从datacamp获得的代码,我正在尝试将其更改为适合我的代码,但显然它不起作用,因为我不知道如何正确地迭代列:

for country in ['fake news IT', 'fake news BR', 'fake news PH']:
    df = df_fake_news[df_fake_news[0] == country]
    fig.add_trace(go.Scatter(
                   x=df['date'],
                   y=df['country'],
                   name=, mode='lines'))

Tags: 数据代码in名称图形示例类型df
1条回答
网友
1楼 · 发布于 2024-06-07 16:49:23

如果要循环遍历数据帧的列,可以直接写入列名,但可以使用df.columns获取列名列表。使用子图水平排列三列

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import numpy as np
import pandas as pd

df = pd.DataFrame({'date':pd.date_range('2020-09-30',' 2021-09-30', freq='1d'),
                   'fake news IT': np.random.randint(0,30,(366,)),
                   'fake news BR': np.random.randint(0,30,(366,)),
                   'fake news PH': np.random.randint(0,30,(366,)),
                  })
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)

fig = make_subplots(rows=1, cols=3)

for i,c in enumerate(df.columns):
    fig.add_trace(
        go.Scatter(x=df.index, y=df[c], mode='markers', name=c),
        row=1, col=i+1
)

fig.show()

enter image description here

相关问题 更多 >

    热门问题