简体   繁体   中英

How to create a simple interactive plotly graph with this dataframe

I am trying to make an interactive graph using an example I saw on datacamp but I don't know how to go about it with a different kind of dataframe. This is my dataframe (I created it myself by adding columns from other dfs):

在此处输入图片说明

How do I iterate through the columns with different names? and how to select the date column ?

This is the code I got from datacamp, I am trying to change it to work for me but obviously it doesn't work because I don't know how to iterate through columns properly:

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'))

If you want to loop through the columns of the dataframe, you can write the column names directly, but you can use df.columns to get a list of column names. Use subplot to arrange the three columns horizontally.

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()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM