Line Chart With Two Y-Axis In Python

Friday, October 20th 2023. | Chart Templates
python Multiple y axis using matplotlib not working Stack Overflow
python Multiple y axis using matplotlib not working Stack Overflow from stackoverflow.com

Line charts are a popular visualization tool used to display trends over time or compare different data sets. Python provides several libraries, such as Matplotlib and Plotly, that allow you to create line charts with ease. In this article, we will focus on creating line charts with two y-axes in Python, which can be useful when you have two different data sets with different scales that you want to compare.

Sample Line Charts with Two Y-Axes

Let’s start with some sample line charts that demonstrate the use of two y-axes. We will be using the Matplotlib library for these examples.

Sample 1: Temperature and Humidity

Suppose you have a dataset that contains daily temperature and humidity measurements. You can create a line chart with two y-axes to visualize the trends of both variables over time. Here’s an example code snippet:

 import matplotlib.pyplot as plt # Sample data days = [1, 2, 3, 4, 5, 6, 7] temperature = [25, 26, 27, 28, 29, 30, 31] humidity = [40, 45, 50, 55, 60, 65, 70] # Create figure and axis objects fig, ax1 = plt.subplots() # Plot temperature on the first y-axis ax1.plot(days, temperature, color='red') ax1.set_xlabel('Days') ax1.set_ylabel('Temperature (°C)', color='red') # Create a second y-axis ax2 = ax1.twinx() # Plot humidity on the second y-axis ax2.plot(days, humidity, color='blue') ax2.set_ylabel('Humidity (%)', color='blue') # Show the plot plt.show() 

In this example, we first import the Matplotlib library and define our sample data. We then create a figure and axis object using the subplots() function. The ax1 object represents the first y-axis, and we plot the temperature data on it using the plot() function. We set the x-axis label and the y-axis label for temperature using the set_xlabel() and set_ylabel() functions, respectively.

To create a second y-axis, we use the twinx() function, which creates a twin Axes sharing the x-axis. We plot the humidity data on the second y-axis and set the y-axis label accordingly. Finally, we use the show() function to display the plot.

Sample 2: Stock Prices and Trading Volume

Another common use case for line charts with two y-axes is to compare stock prices with trading volume. Here’s an example code snippet:

 import matplotlib.pyplot as plt # Sample data days = [1, 2, 3, 4, 5, 6, 7] stock_prices = [100, 105, 110, 120, 115, 105, 100] trading_volume = [1000, 1200, 1500, 2000, 1800, 1500, 1200] # Create figure and axis objects fig, ax1 = plt.subplots() # Plot stock prices on the first y-axis ax1.plot(days, stock_prices, color='green') ax1.set_xlabel('Days') ax1.set_ylabel('Stock Prices ($)') # Create a second y-axis ax2 = ax1.twinx() # Plot trading volume on the second y-axis ax2.plot(days, trading_volume, color='purple') ax2.set_ylabel('Trading Volume') # Show the plot plt.show() 

In this example, we have a dataset that contains daily stock prices and trading volume. We follow a similar approach as in the previous example to create a line chart with two y-axes. The only difference is the color of the lines and the labels for the y-axes.

Sample 3: Sales and Advertising Expenses

Let’s consider a scenario where you want to visualize the relationship between sales and advertising expenses. Here’s an example code snippet:

 import matplotlib.pyplot as plt # Sample data months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'] sales = [10000, 12000, 15000, 18000, 20000, 22000, 24000] advertising_expenses = [2000, 2500, 3000, 3500, 4000, 4500, 5000] # Create figure and axis objects fig, ax1 = plt.subplots() # Plot sales on the first y-axis ax1.plot(months, sales, color='orange') ax1.set_xlabel('Months') ax1.set_ylabel('Sales') # Create a second y-axis ax2 = ax1.twinx() # Plot advertising expenses on the second y-axis ax2.plot(months, advertising_expenses, color='brown') ax2.set_ylabel('Advertising Expenses') # Show the plot plt.show() 

In this example, we have monthly sales data and corresponding advertising expenses. We plot the sales data on the first y-axis and the advertising expenses on the second y-axis. The labels and colors for the lines are adjusted accordingly.

Sample 4: Website Traffic and Conversion Rate

Suppose you want to analyze the relationship between website traffic and conversion rate. Here’s an example code snippet:

 import matplotlib.pyplot as plt # Sample data months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'] website_traffic = [1000, 1200, 1500, 1800, 2000, 2200, 2400] conversion_rate = [0.1, 0.12, 0.15, 0.2, 0.18, 0.2, 0.22] # Create figure and axis objects fig, ax1 = plt.subplots() # Plot website traffic on the first y-axis ax1.plot(months, website_traffic, color='blue') ax1.set_xlabel('Months') ax1.set_ylabel('Website Traffic') # Create a second y-axis ax2 = ax1.twinx() # Plot conversion rate on the second y-axis ax2.plot(months, conversion_rate, color='green') ax2.set_ylabel('Conversion Rate') # Show the plot plt.show() 

In this example, we have monthly website traffic data and the corresponding conversion rates. We plot the website traffic on the first y-axis and the conversion rates on the second y-axis.

Sample 5: Revenue and Expenses

Let’s consider a scenario where you want to compare revenue and expenses over a period of time. Here’s an example code snippet:

 import matplotlib.pyplot as plt # Sample data months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'] revenue = [10000, 12000, 15000, 18000, 20000, 22000, 24000] expenses = [8000, 9000, 10000, 11000, 12000, 13000, 14000] # Create figure and axis objects fig, ax1 = plt.subplots() # Plot revenue on the first y-axis ax1.plot(months, revenue, color='red') ax1.set_xlabel('Months') ax1.set_ylabel('Revenue') # Create a second y-axis ax2 = ax1.twinx() # Plot expenses on the second y-axis ax2.plot(months, expenses, color='purple') ax2.set_ylabel('Expenses') # Show the plot plt.show() 

In this example, we have monthly revenue and expenses data. We plot the revenue on the first y-axis and the expenses on the second y-axis.

Frequently Asked Questions (FAQ)

1. Can I create line charts with two y-axes in Python using other libraries?

Yes, besides Matplotlib, you can also create line charts with two y-axes using libraries like Plotly and Seaborn. Each library may have slightly different syntax and functionality, so it’s worth exploring the documentation for the specific library you are using.

2. How do I customize the appearance of the line chart?

You can customize various aspects of the line chart, such as the line colors, line styles, markers, axis labels, titles, and more. Each library provides different functions and parameters for customization. Refer to the documentation of the library you are using for detailed instructions.

3. Can I add more than two y-axes to a line chart?

Yes, it is possible to add more than two y-axes to a line chart. However, adding too many y-axes can make the chart cluttered and difficult to interpret. It is generally recommended to limit the number of y-axes to two or three for better readability.

tags: , ,