Below is an example Python code using the matplotlib library to generate a scatter plot with multiple Y-axes. This example will create a figure with one X-axis and two Y-axes (a left Y-axis and a right Y-axis), each displaying different sets of data points. We'll plot the relationship between x and two different y variables (y1 and y2) on the same scatter plot but with separate Y-axes.
First, ensure you have matplotlib installed. If not, you can install it using pip:
bash
pip install matplotlib numpy
Here's the Python code for the scatter plot with multiple Y-axes:
python
import matplotlib.pyplot as plt
import numpy as np
# Sample data generation
np.random.seed(0)
x = np.arange(1, 11) # X-axis values
y1 = np.random.randint(1, 100, 10) # Data for left Y-axis
y2 = np.random.randint(100, 1000, 10) # Data for right Y-axis
# Create the figure and axis
fig, ax1 = plt.subplots()
# Plot data for the left Y-axis
color = 'tab:red'
ax1.set_xlabel('X Values')
ax1.set_ylabel('Y1 Values (Left)', color=color)
ax1.scatter(x, y1, color=color)
ax1.tick_params(axis='y', labelcolor=color)
# Create a second axis on the right
ax2 = ax1.twinx()
# Plot data for the right Y-axis
color = 'tab:blue'
ax2.set_ylabel('Y2 Values (Right)', color=color)
ax2.scatter(x, y2, color=color, marker="x") # Using a different marker for clarity
ax2.tick_params(axis='y', labelcolor=color)
# Set title
fig.tight_layout() # To ensure labels fit within the figure
plt.title('Scatter Plot with Multiple Y-Axes')
plt.show()
Explanation:
Import Libraries: We import matplotlib.pyplot for plotting and numpy for generating sample data.
Generate Sample Data: We create arrays for x, y1, and y2 values. y1 and y2 are generated with different scales to demonstrate the multiple Y-axes functionality.
Create Figure and Axis: plt.subplots() creates a figure and a set of subplots (in this case, one).
Plot for Left Y-Axis (y1): We plot y1 against x and customize the left Y-axis.
Create Second Axis: .twinx() creates a second Y-axis that shares the same X-axis.
Plot for Right Y-Axis (y2): We plot y2 against x (same x values) and customize the right Y-axis. A different marker ("x") is used for y2 to distinguish it from y1 in the scatter plot.
Final Customizations: We add labels, title, and ensure the layout fits all elements with fig.tight_layout().
Display Plot: Finally, plt.show() displays the plot.
Example Use Cases:
Scientific Research: Visualizing experimental data where two different measurements (e.g., temperature and pressure) are taken over the same range of conditions (e.g., time or concentration).
Financial Analysis: Plotting stock prices (one scale) against trading volumes (another scale) over time to analyze market trends.
Engineering: Displaying sensor readings, such as pressure and flow rate, against a common variable like time or distance, to monitor system performance.