The Magic of Python Visualization: A Complete Guide to Creating Dual-Axis Charts (2024)

Have you ever fallen in love with dual-axis charts, a new way to look at data? Python Visualization is no longer the domain of experts, and today we're going to take you on a journey to create beautiful charts using Python.

이중축 차트 예시 그림

Understanding dual-axis charts

A dual-axis chart is a powerful visualization tool that allows you to effectively represent data with different scales on a single graph. They're especially useful for simultaneously representing data with very different ranges, such as stock prices and trading volumes.

Python visualization code

import matplotlib.pyplot as plt
import numpy as np

Prepare the # data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = 100 * np.cos(x)

Generate the # graph
fig, ax1 = plt.subplots(figsize=(10, 6))

# Set the first y-axis
color = 'tab:blue'
ax1.set_xlabel('X axis')
ax1.set_ylabel('First Y axis', color=color)
line1 = ax1.plot(x, y1, color=color, label='Sin')
ax1.tick_params(axis='y', labelcolor=color)

# Create a second y-axis
ax2 = ax1.twinx()
color = 'tab:red'
ax2.set_ylabel('Second Y axis', color=color)
line2 = ax2.plot(x, y2, color=color, label='Cos')
ax2.tick_params(axis='y', labelcolor=color)

plt.title('Python Visualization: Dual Axis Chart Example')
plt.show()

Cautions for using dual-axis charts

Dual-axis charts are a powerful tool, but they should be used with care. Here are some key caveats to consider when building a dual-axis chart:

Managing data scale

  • Scale settings should be chosen carefully; incorrect scaling can skew data interpretation.
  • You need to adjust the scales so that the relationship between the two data series is clear.

Visual clarity

  • Each axis and data series has a distinct color.
  • Position the legend appropriately to ensure readability.
  • Add grid lines to make your data easier to read.

Consider alternatives

  • If the data series are too different, consider separating them into separate charts.
  • Using index charts or normalized values can also be a good alternative.

Use cases

Among Python visualization techniques, bi-axis charts are useful in many areas, but they are particularly valuable in the following situations:

Stock market analysis

  • Show stock price and volume simultaneously to understand the relationship between price changes and trading activity.
  • Analyze trends and momentum by displaying stock prices alongside technical indicators (e.g. MACD, RSI)

Analyze weather data

  • Show temperature and precipitation at the same time to get a comprehensive view of weather patterns.
  • Show temperature and humidity together to analyze complex weather phenomena, such as body temperature or malaise index.

Analyze economic indicators

  • Visualize the relationship between GDP and unemployment to understand the connection between economic growth and the job market.
  • You can analyze the effects of monetary policy by showing inflation and interest rates simultaneously.

Analyze marketing performance

  • You can evaluate your marketing efficiency by showing ad spend and revenue at the same time.
  • You can analyze the effectiveness of your marketing campaigns by showing customer acquisition and conversion rates together.

Analyze energy consumption

  • You can see how weather affects energy demand by displaying power consumption and outside temperature at the same time.
  • You can analyze energy transition trends by comparing renewable energy production to fossil fuel usage.

Dual-axis charts allow you to effectively compare data with different units or scales, which can help you intuitively understand complex relationships. However, when using them, you should pay attention to the scale settings to ensure that they don't skew your interpretation of the data.

# Another example

이중축 차트 예시2 그림

# code block

import matplotlib.pyplot as plt
import numpy as np

Prepare the # data
x = np.range(0, 10, 1)
y1 = np.random.randint(1, 10, size=10)
y2 = np.random.randint(10, 100, size=10)

Generate a # graph
fig, ax1 = plt.subplots(figsize=(10, 6))

# Set first y-axis (bar graph)
color = 'tab:purple'
ax1.set_xlabel('X axis')
ax1.set_ylabel('First Y axis', color=color)
ax1.bar(x, y1, color=color, alpha=0.6, label='Data 1')
ax1.tick_params(axis='y', labelcolor=color)

# Create a second y-axis (line graph)
twin_ax = ax1.twinx()
color = 'tab:pink'
twin_ax.set_ylabel('Second Y axis', color=color)
twin_ax.plot(x, y2, color=color, marker='o', label='Data 2')
twin_ax.tick_params(axis='y', labelcolor=color)

Setting the # title and legend
plt.title('Dual Axis Chart Example: Bar and Line Graph')
fig.tight_layout()
plt.show()

# code commentary

  1. Import the required libraries (matplotlib, numpy).
  2. Use NumPy to generate x-axis data and two y-axis data (y1, y2).
  3. plt.subplots()to create a graph object and the first axis (ax1).
  4. Make settings for the first y-axis:
    • Display the Y1 data in a purple bar graph.
    • Set the x-axis and y-axis labels.
  5. ax1.twinx()to create a second y-axis (twin_ax):
    • Show the Y2 data in a pink line graph.
    • Set a second y-axis label.
  6. Set a title for the graph, tight_layout()to adjust the layout and then display the graph.

# Glossary

  • Dual Axis ChartA type of chart that uses two y-axes in one graph to simultaneously represent data series with different scales or units.
  • matplotlibA data visualization library for the Python programming language that allows you to create various types of graphs and charts.
  • NumPyA Python library for numerical computation that allows you to efficiently handle large multidimensional arrays and matrices.
  • plt.subplots(): Function in matplotlib that creates a new Figure and one or more Axes.
  • ax1.twinx(): matplotlib method that creates a new y-axis while sharing the x-axis with an existing axis. Used when creating dual-axis charts.
  • tight_layout(): A function in matplotlib that automatically adjusts the spacing between graph elements to avoid overlapping.
  • ScaleThe unit or range in which data values are represented in a graph. In a dual-axis chart, a different scale can be used for each axis.
  • NormalizationThe process of converting data from different ranges to a common scale. Can be used as an alternative to a dual-axis chart.

If you're interested in charts like this, you're probably also interested in unusual graphs that can be visualized in Python. Create a graph comparing grade changes with Python visualizations: color-code score increases/decreases Check out the post for some unique graphs!

Similar Posts