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'))
CodePudding user response:
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()