Plotly multiple dataframes

Plotly Multiple Dataframes

Plotly is a powerful Python library used for interactive data visualization. It supports various types of charts and can handle multiple dataframes easily. Let’s take a look at how to use Plotly with multiple dataframes.

Example 1: Line Chart

Let’s say we have two dataframes, df1 and df2, with x and y values for each dataframe. We want to create a line chart with two lines, representing the data from both dataframes.

    
import plotly.graph_objects as go
import pandas as pd

# Create dataframe 1
df1 = pd.DataFrame({'x': [1, 2, 3, 4, 5], 'y': [1, 4, 9, 16, 25]})

# Create dataframe 2
df2 = pd.DataFrame({'x': [1, 2, 3, 4, 5], 'y': [1, 8, 27, 64, 125]})

# Create line chart
fig = go.Figure()

# Add trace for dataframe 1
fig.add_trace(go.Scatter(x=df1['x'], y=df1['y'], name='Dataframe 1'))

# Add trace for dataframe 2
fig.add_trace(go.Scatter(x=df2['x'], y=df2['y'], name='Dataframe 2'))

# Display chart
fig.show()
    
  

In this example, we first import the necessary libraries. Then, we create two dataframes, df1 and df2, with x and y values. We create a new figure object using go.Figure(). We add two traces to the figure, each representing the data from one dataframe, using go.Scatter(). Finally, we call fig.show() to display the chart.

Example 2: Bar Chart

Let’s consider another example where we want to create a bar chart with multiple dataframes.

    
import plotly.graph_objects as go
import pandas as pd

# Create dataframe 1
df1 = pd.DataFrame({'category': ['A', 'B', 'C'], 'value': [10, 20, 30]})

# Create dataframe 2
df2 = pd.DataFrame({'category': ['A', 'B', 'C'], 'value': [40, 50, 60]})

# Create bar chart
fig = go.Figure()

# Add trace for dataframe 1
fig.add_trace(go.Bar(x=df1['category'], y=df1['value'], name='Dataframe 1'))

# Add trace for dataframe 2
fig.add_trace(go.Bar(x=df2['category'], y=df2['value'], name='Dataframe 2'))

# Display chart
fig.show()
    
  

In this example, we have two dataframes, df1 and df2, with categories and corresponding values. We create a new figure object using go.Figure(). We add two traces to the figure, each representing the data from one dataframe, using go.Bar(). Finally, we call fig.show() to display the chart.

These are just a few examples of how you can use Plotly with multiple dataframes. With Plotly, you have a wide range of chart types and customization options to create interactive and visually appealing visualizations.

Leave a comment