Search code examples
pythonpandasplotlyplotly-dashstreamlit

Using Plotly to create a graph with columns from different dataframes


I have this code below which is running very well. However, I want to use plotly to create the same graph. How can I convert this code such that it uses plotly to plot the graph?

> dict1 = {'Date': ['2022-12-02', '2022-12-16', '2023-01-15'], 'Impressions': [20, 21, 19]}
dict2 = {'Date': ['2022-08-02', '2022-09-16', '2023-02-20'], 'Impressions': [18, 51, 48]}

df1 = pd.DataFrame(dict1)
df2 = pd.DataFrame(dict2)

df1['Date'] = pd.to_datetime(df1['Date'])
df2['Date'] = pd.to_datetime(df2['Date'])

fig, ax = plt.subplots()
ax2 = ax.twinx()

df1.plot(x="Date", y="Impressions", ax=ax)
df2.plot(x="Date", y="Impressions", ax=ax2, ls="--")

plt.show()

enter image description here


Solution

  • You can replace the Matplotlib plot creation and rendering functions with equivalent Plotly functions (go.Figure(), go.Scatter(), and update_layout()) while preserving the data manipulation and conversion steps.

    Here is how you can achieve this:

    import plotly.graph_objects as go
    import pandas as pd
    
    dict1 = {'Date': ['2022-12-02', '2022-12-16', '2023-01-15'], 'Impressions': [20, 21, 19]}
    dict2 = {'Date': ['2022-08-02', '2022-09-16', '2023-02-20'], 'Impressions': [18, 51, 48]}
    
    df1 = pd.DataFrame(dict1)
    df2 = pd.DataFrame(dict2)
    
    df1['Date'] = pd.to_datetime(df1['Date'])
    df2['Date'] = pd.to_datetime(df2['Date'])
    
    fig = go.Figure()
    
    fig.add_trace(go.Scatter(
        x=df1['Date'],
        y=df1['Impressions'],
        name='Data 1',
        mode='lines'
    ))
    
    fig.add_trace(go.Scatter(
        x=df2['Date'],
        y=df2['Impressions'],
        name='Data 2',
        mode='lines',
        line=dict(dash='dash')
    ))
    
    fig.update_layout(
        title='Impressions Over Time',
        xaxis=dict(title='Date'),
        yaxis=dict(title='Impressions')
    )
    
    fig.show()
    

    Output Graph