Python plot with two axes

Dual Axis plots in Python

This article discusses how to add a secondary axis to Python plots

At times, we may need to add two variables with different scale to an axis of a plot. For example, we want to have GDP per capita (in $) and annual GDP growth % in the y-axis and year in the x-axis. In other words, we need to visualize the trend in GDP per capita ($) and GDP growth rate across years. Since, GDP per capita ($) and GDP growth rate have different scale. Plotting both of them using the same y-axis would undermine the other.

In the above plot, we can see that the trend in Annual Growth Rate is completely undermined by the GDP per capita ($). In the plot below, we see that using a logarithmic scale in y-axis also didn’t help.

This makes it essential to have a secondary y-axis for Annual growth rate (%). to illustrate the addition of a secondary axis, we’ll use the data frame (named ‘gdp’) shown below containing GDP per capita ($) and Annual growth rate (%) data from the year 2000 to 2020.

In the next example, we’ll plot the trend in Nifty (a stock index in India) along with the volume. In this example, we’ll use line plot for index value and bar plot for volume. Below are the first few records of the data frame (named ‘nifty_2021’) that we’ll use in this example.

This brings this article to an end. We’ve discussed how variables with different scale may pose a problem in plotting them together and saw how adding a secondary axis solves the problem. We’ve also seen how to plot a line and bar plot using secondary axis.

Источник

Multiple Axes in Python

How to make a graph with multiple axes (dual y-axis plots, plots with secondary axes) in python.

This page in another language

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Multiple Y Axes and Plotly Express¶

Note: At this time, Plotly Express does not support multiple Y axes on a single figure. To make such a figure, use the make_subplots() function in conjunction with graph objects as documented below.

Two Y Axes¶

import plotly.graph_objects as go from plotly.subplots import make_subplots # Create figure with secondary y-axis fig = make_subplots(specs=[["secondary_y": True>]]) # Add traces fig.add_trace( go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis data"), secondary_y=False, ) fig.add_trace( go.Scatter(x=[2, 3, 4], y=[4, 5, 6], name="yaxis2 data"), secondary_y=True, ) # Add figure title fig.update_layout( title_text="Double Y Axis Example" ) # Set x-axis title fig.update_xaxes(title_text="xaxis title") # Set y-axes titles fig.update_yaxes(title_text="primary yaxis title", secondary_y=False) fig.update_yaxes(title_text="secondary yaxis title", secondary_y=True) fig.show() 

Multiple axes in Dash¶

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash , click «Download» to get the code and run python app.py .

Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.

Sign up for Dash Club → Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now.

Multiple Y-Axes Subplots¶

import plotly.graph_objects as go from plotly.subplots import make_subplots fig = make_subplots(rows=2, cols=2, specs=[["secondary_y": True>, "secondary_y": True>], ["secondary_y": True>, "secondary_y": True>]]) # Top left fig.add_trace( go.Scatter(x=[1, 2, 3], y=[2, 52, 62], name="yaxis data"), row=1, col=1, secondary_y=False) fig.add_trace( go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis2 data"), row=1, col=1, secondary_y=True, ) # Top right fig.add_trace( go.Scatter(x=[1, 2, 3], y=[2, 52, 62], name="yaxis3 data"), row=1, col=2, secondary_y=False, ) fig.add_trace( go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis4 data"), row=1, col=2, secondary_y=True, ) # Bottom left fig.add_trace( go.Scatter(x=[1, 2, 3], y=[2, 52, 62], name="yaxis5 data"), row=2, col=1, secondary_y=False, ) fig.add_trace( go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis6 data"), row=2, col=1, secondary_y=True, ) # Bottom right fig.add_trace( go.Scatter(x=[1, 2, 3], y=[2, 52, 62], name="yaxis7 data"), row=2, col=2, secondary_y=False, ) fig.add_trace( go.Scatter(x=[1, 2, 3], y=[40, 50, 60], name="yaxis8 data"), row=2, col=2, secondary_y=True, ) fig.show() 

Multiple Axes¶

Low-level API for creating a figure with multiple axes

import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x=[1, 2, 3], y=[4, 5, 6], name="yaxis1 data" )) fig.add_trace(go.Scatter( x=[2, 3, 4], y=[40, 50, 60], name="yaxis2 data", yaxis="y2" )) fig.add_trace(go.Scatter( x=[4, 5, 6], y=[40000, 50000, 60000], name="yaxis3 data", yaxis="y3" )) fig.add_trace(go.Scatter( x=[5, 6, 7], y=[400000, 500000, 600000], name="yaxis4 data", yaxis="y4" )) # Create axis objects fig.update_layout( xaxis=dict( domain=[0.3, 0.7] ), yaxis=dict( title="yaxis title", titlefont=dict( color="#1f77b4" ), tickfont=dict( color="#1f77b4" ) ), yaxis2=dict( title="yaxis2 title", titlefont=dict( color="#ff7f0e" ), tickfont=dict( color="#ff7f0e" ), anchor="free", overlaying="y", side="left", position=0.15 ), yaxis3=dict( title="yaxis3 title", titlefont=dict( color="#d62728" ), tickfont=dict( color="#d62728" ), anchor="x", overlaying="y", side="right" ), yaxis4=dict( title="yaxis4 title", titlefont=dict( color="#9467bd" ), tickfont=dict( color="#9467bd" ), anchor="free", overlaying="y", side="right", position=0.85 ) ) # Update layout properties fig.update_layout( title_text="multiple y-axes example", width=800, ) fig.show() 

Automatically Shifting Axes¶

To automatically reposition axes to avoid overlap with other axes with the same overlaying value, set autoshift=True . For autoshift to work on an axis, you’ll also need to set anchor=»free» on that axis.

import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6], name="yaxis data")) fig.add_trace(go.Scatter(x=[2, 3, 4], y=[40, 50, 60], name="yaxis2 data", yaxis="y2")) fig.add_trace( go.Scatter(x=[4, 5, 6], y=[1000, 2000, 3000], name="yaxis3 data", yaxis="y3") ) fig.add_trace( go.Scatter(x=[3, 4, 5], y=[400, 500, 600], name="yaxis4 data", yaxis="y4") ) fig.update_layout( xaxis=dict(domain=[0.25, 0.75]), yaxis=dict( title="yaxis title", ), yaxis2=dict( title="yaxis2 title", overlaying="y", side="right", ), yaxis3=dict(title="yaxis3 title", anchor="free", overlaying="y", autoshift=True), yaxis4=dict( title="yaxis4 title", anchor="free", overlaying="y", autoshift=True, ), ) fig.update_layout( title_text="Shifting y-axes with autoshift", ) fig.show() 

Источник

How to Make a Plot with Two Different Y-axis in Python with Matplotlib ?

Sometimes, as part of a quick exploratory data analysis, you may want to make a single plot containing two variables with different scales.

One of the options is to make a single plot with two different y-axis, such that the y-axis on the left is for one variable and the y-axis on the right is for the y-variable.

If you try to plot the two variables on a same plot without having two different y-axis, the plot would not really make sense.

If the variables have very different scales, you’ll want to make sure that you plot them in different twin Axes objects. These objects can share one axis (for example, the time, or x-axis) while not sharing the other (the y-axis).

To create a twin Axes object that shares the x-axis, we use the twinx method.

# import pandas import pandas as pd

We will use gapminder data from Carpentries to make the plot with two different y-axis on the same plot.

# Carpentries link for gapminder data data_url = 'http://bit.ly/2cLzoxH' #load gapminder data from url as pandas dataframe gapminder = pd.read_csv(data_url) print(gapminder.head(3))

Let us subset gapminder data by using Pandas query() function to filter for rows with United States.

gapminder_us = gapminder[gapminder.country=="United States"]

We are interested in making a plot of how lifeExp & gdpPercap changes over the years. The variable on x-axis is year and on y-axis we are interested in lifeExp & gdpPercap.
Both lifeExp and gdpPercap have different ranges. lifeExp values are below 100 and gdpPercap values are in thousands.

Naively, let us plot both on the same plot with a single y-axis.

# create figure and axis objects with subplots() fig,ax=plt.subplots() ax.plot(gapminder_us.year, gapminder_us.lifeExp, marker="o") ax.set_xlabel("year") ax.set_ylabel("lifeExp") ax.plot(gapminder_us.year, gapminder_us["gdpPercap"], marker="o") plt.show()

We can immediately see that this is a bad idea. The line for lifeExp over years is flat and really low. We don’t see any variation in it because of the scale of gdpPercap values.

Plotting variables of different scale in matplotlib

One of the solutions is to make the plot with two different y-axes. The way to make a plot with two different y-axis is to use two different axes objects with the help of twinx() function.

We first create figure and axis objects and make a first plot. In this example, we plot year vs lifeExp. And we also set the x and y-axis labels by updating the axis object.

# create figure and axis objects with subplots() fig,ax = plt.subplots() # make a plot ax.plot(gapminder_us.year, gapminder_us.lifeExp, color="red", marker="o") # set x-axis label ax.set_xlabel("year", fontsize = 14) # set y-axis label ax.set_ylabel("lifeExp", color="red", fontsize=14)

Next we use twinx() function to create the second axis object “ax2”. Now we use the second axis object “ax2” to make plot of the second y-axis variable and update their labels.

# twin object for two different y-axis on the sample plot ax2=ax.twinx() # make a plot with different y-axis using second axis object ax2.plot(gapminder_us.year, gapminder_us["gdpPercap"],color="blue",marker="o") ax2.set_ylabel("gdpPercap",color="blue",fontsize=14) plt.show() # save the plot as a file fig.savefig('two_different_y_axis_for_single_python_plot_with_twinx.jpg', format='jpeg', dpi=100, bbox_inches='tight')

Then we can display the plot with plt.show() as before.

Now we have what we wanted. A plot with with different y-axis made with twinx in matplotlib. This definitely help us understand the relationship of the two variables against another. We can see that both lifeExp and gdpPerCap have increased over the years.

Plot with two different y-axis with twinx in Python

Although a plot with two y-axis does help see the pattern, personally I feel this is bit cumbersome. A better solution to use the idea of “small multiples”, two subplots with same x-axis. We will see an example of that soon.

Источник

Читайте также:  Selenium webdriver python yandex browser
Оцените статью