π‘ Problem Formulation: When displaying two datasets with different scales together on a single chart, it’s essential to create a secondary y-axis for clear and accurate data representation. This is often required when combining datasets like temperature and precipitation or stock prices with volume traded, where each dataset varies drastically in scale and requires separate axes to make sense of the data visually. Our goal is to showcase several methods to plot on a secondary y-axis using Python’s Plotly library.
Method 1: Create a Secondary Y-Axis Using make_subplots
Plotly’s make_subplots
function is key for creating figures with secondary y-axes. This method involves initializing a subplot with two y-axes and then adding traces for each dataset. The secondary_y
parameter is crucial for specifying which trace should be linked to the second y-axis.
Here’s an example:
from plotly.subplots import make_subplots import plotly.graph_objs as go fig = make_subplots(specs=[[{"secondary_y": True}]]) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), secondary_y=False) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[400, 500, 600]), secondary_y=True) fig.update_yaxes(title_text="Primary Y-Axis", secondary_y=False) fig.update_yaxes(title_text="Secondary Y-Axis", secondary_y=True) fig.show()
Output: A Plotly figure with two lines on different y-axes.
This code snippet first initializes a figure with two y-axes, then adds two scatter plots. The first scatter is linked to the primary y-axis (default), and the second is linked to the secondary y-axis by setting the secondary_y
parameter to True
. The y-axes are then labeled appropriately.
Method 2: Update Existing Figures with add_trace
and the secondary_y
Parameter
If you already have a figure and want to add a secondary y-axis, you can use the add_trace
method along with the secondary_y
parameter. This is useful for incrementally building complex figures.
Here’s an example:
import plotly.graph_objs as go from plotly.subplots import make_subplots fig = make_subplots(specs=[[{"secondary_y": True}]]) fig.add_trace(go.Bar(x=[1, 2, 3], y=[40, 50, 60]), secondary_y=False) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), secondary_y=True) fig.update_layout(title_text="Bar and Scatter Plot on Different Y-Axes") fig.show()
Output: A Plotly figure with a bar chart and a scatter plot on different y-axes.
This approach starts again by creating a subplot with two y-axes. A bar chart is first added and is set on the primary y-axis. Then, a scatter plot is added using the add_trace
method with the secondary_y
parameter set to True
to indicate it should be plotted on the secondary axis.
Method 3: Using Figure Factory
to Create Dual-Axis Charts
The Figure Factory
module within Plotly has high-level functions for creating specific plot types, including dual-axis charts. The functionality is less flexible than make_subplots
, but it can be simpler for quick applications.
Here’s an example:
import plotly.figure_factory as ff import numpy as np x = np.linspace(0, 1, 100) y1 = np.cumsum(np.random.randn(100)) y2 = np.cumsum(np.random.randn(100)) fig = ff.create_dual_axis_lines_figure(inds=x, left_data=y1, right_data=y2) fig.show()
Output: A Plotly figure with two datasets plotted on different y-axes.
This code snippet leverages Plotly’s Figure Factory
to conveniently create a line chart with dual y-axes. By providing the x-axis values and the two separate y-axis datasets, create_dual_axis_lines_figure
generates the desired visualization with minimal effort.
Method 4: Overlaying Traces with Different Axes
Sometimes you wish to add a different y-axis while maintaining the layout of existing traces. You can overlay the new trace over the existing ones by carefully adjusting the axis parameters.
Here’s an example:
import plotly.graph_objs as go trace0 = go.Scatter(x=[1, 2, 3], y=[4, 5, 6]) trace1 = go.Scatter(x=[1, 2, 3], y=[14, 15, 16], yaxis='y2') fig = go.Figure(data=[trace0, trace1]) fig.update_layout(yaxis2=dict(overlaying='y', side='right')) fig.show()
Output: A Plotly figure with two overlaid traces on different y-axes.
The code snippet illustrates the overlaying of a trace on an existing y-axis. After creating two Scatter instances, the second trace defines a different y-axis using the parameter yaxis='y2'
. In the layout of the figure, yaxis2
is configured to overlay ‘y’ and appear on the right side.
Bonus One-Liner Method 5: Quick Configuration with Dictionary Syntax
Sometimes you need a quick and dirty way to set a secondary y-axis. You can do this in a single line by passing a dictionary with the required properties directly into the layout update.
Here’s an example:
import plotly.graph_objs as go fig = go.Figure() fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6])) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[40, 50, 60], yaxis='y2')) fig.update_layout({'yaxis2': {'overlaying': 'y', 'side': 'right'}}) fig.show()
Output: A Plotly figure with two traces using different y-axes.
By adding traces to a figure and then using dictionary syntax to update the layout, we provide a secondary y-axis configuration. The yaxis='y2'
in the second trace dictates the use of an additional axis, which is then defined and customized using the layout dictionary.
Summary/Discussion
- Method 1: make_subplots. Versatile and robust. Ideal for complex layout management. Can be verbose for simple use cases.
- Method 2: add_trace with secondary_y. Incremental and straightforward. Best when adding to existing plots. Less control over subplot creation than Method 1.
- Method 3: Figure Factory. Simple, but less flexible. Great for standard dual-axis line charts without requiring fine-tuned customizations.
- Method 4: Overlaying Traces. Offers fine control over axis overlays. Requires understanding of axis settings which might be confusing to beginners.
- Bonus Method 5: Dictionary Syntax. Quick, one-liner solution. Offers less readability but is highly convenient for seasoned coders familiar with Plotly’s layout options.