How to ensure there is an x and y margin when using twinx and twiny

101 Views Asked by At

I am trying to create a scatter plot like the desired image, but my code doesn't have space before 1 or after 7.

How can I fix the problem?

import numpy as np
import matplotlib.pyplot as plt

# Set the size of the figure and create subplots
fig, axes = plt.subplots(2,1, figsize=(6, 12))

# Number of data points
num_points = 24

# Generate random data for locations, sizes, and colors
x = np.random.normal(4, 1.5, num_points)
y = np.random.normal(4, 1.5, num_points)
sizes = np.random.uniform(50, 200, num_points)
colors = np.random.rand(num_points, 3)  # Random RGB colors

# Create the scatter plots
for ax in axes:
    ax.scatter(x, y, s=sizes, c=colors, alpha=0.7, edgecolors='k', linewidths=1)

# Set tick positions and labels for the bottom scatter plot
for ax in axes:
    ax.set_xticks(np.arange(1, 8))  # Set x-axis ticks to 1 through 7
    ax.set_yticks(np.arange(1, 8))  # Set y-axis ticks to 1 through 7
    ax.set_xticklabels([str(i) for i in range(1, 8)])
    ax.set_yticklabels([str(i) for i in range(1, 8)])
    
# Set axis labels and titles for the bottom scatter plot
# Add a secondary y-axis on the right for the top plot
axes2 = axes[0].twinx()
axes2.set_ylabel('Y-axis 2 (Top)')
axes2.set_yticks(np.arange(1, 8))  # Set x-axis ticks to 1 through 7

# Add a secondary x-axis on the top plot and set its ticks and labels
axes2x = axes[0].twiny()
axes2x.set_xlabel('X-axis 2 (Top)')
axes2x.set_xticks(np.arange(1, 8))  # Set x-axis ticks to 1 through 7

# Remove x-axis and x-axis labels for the top scatter plot
axes[0].get_xaxis().set_visible(False)
axes[0].set_xlabel('')  # Clear any existing x-axis label

axes1x = axes[1]
axes1x.set_xlabel('X-axis 1 (Bottom)')
axes1x.set_xticks(np.arange(1, 8))

axes1y = axes[1]
axes1y.set_ylabel('Y-axis 1 (Bottom)')
axes1y.set_yticks(np.arange(1, 8))

# Add a secondary y-axis on the right for the bottom plot (ax1)
axes2y = axes[1].twinx()
axes2y.set_ylabel('Y-axis 2 (Bottom)')
axes2y.set_yticks(np.arange(1, 8))  # Set x-axis ticks to 1 through 7

#Name the title
axes[1].set_title('Bottom Scatter Plot')

# Show the plots
plt.show()

Current Result

enter image description here

Desired Scatter plot image (in relation to the margins)

enter image description here

1

There are 1 best solutions below

0
On
  • The primary resolution is to set the limits for each axes as (0, 8), and only set ticks and ticklables on range(1, 8).
    • ax.set(xlim=(0, 8), ylim=(0, 8)) and .set_ylim(0, 8), which looks like this plot before setting the ticks / ticklabels and adding the right y-axis.
    • range(1, 8)[1, 2, 3, 4, 5, 6, 7]
  • For axes[0] it's more efficient to move the xticks, xticklabels, and xlabel to the top, instead of using twiny.
    • If you still want to use axes2x = axes[0].twiny(), then use axes2x.set_xlim(0, 8).
  • Tested in python 3.12.0, matplotlib 3.8.0
# Number of data points
num_points = 24

# Generate random data for locations, sizes, and colors
x = np.random.normal(4, 1.5, num_points)
y = np.random.normal(4, 1.5, num_points)
sizes = np.random.uniform(50, 200, num_points)
colors = np.random.rand(num_points, 3)  # Random RGB colors

# Set the size of the figure and create subplots
fig, axes = plt.subplots(2, 1, figsize=(6, 12))

# ticks and ticklabels
tl = range(1, 8)

# Create the scatter plots
for ax in axes:
    ax.scatter(x, y, s=sizes, c=colors, alpha=0.7, edgecolors='k', linewidths=1)

    # the crucial detail is to set the limits to be 1 before and after the end of the ticks / ticklabels
    ax.set(xlim=(0, 8), ylim=(0, 8))

    # set the ticks and ticklabels at the same time
    ax.set_xticks(tl, tl)
    ax.set_yticks(tl, tl)

# move xaxis to the top
axes[0].xaxis.tick_top()

# set the xaxis label text and position
axes[0].xaxis.set_label_position("top")
axes[0].set_xlabel('X-axis 0 (Top)')

# set the existing axes labels
axes[0].set_ylabel('Y-axis 0 (Top Left)')
axes[1].set_xlabel('X-axis 1 (Bottom)')
axes[1].set_ylabel('Y-axis 1 (Bottom Left)')

# Add a secondary y-axis on the right for the top plot
axes0R = axes[0].twinx()
axes0R.set_ylabel('Y-axis 0 (Top Right)')
axes0R.set_ylim(0, 8)  # set the limits
axes0R.set_yticks(tl)  # Set x-axis ticks to 1 through 7

# Add a secondary y-axis on the right for the bottom plot (ax1)
axes2y = axes[1].twinx()
axes2y.set_ylabel('Y-axis 2 (Bottom)')
axes2y.set_ylim(0, 8)  # set the limits
axes2y.set_yticks(tl)  # Set x-axis ticks to 1 through 7

# set the axes titles
axes[1].set_title('Bottom Scatter Plot')
axes[0].set_title('Top Scatter Plot')

# set the figure title
fig.suptitle('Figure Title')

# Show the plots
plt.show()

enter image description here