matplotlib 如何确保在使用twinx和twiny时有x和y边距

vm0i2vca  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(115)

我试图创建一个散点图像所需的图像,但我的代码没有空间之前1或7后。
我如何解决这个问题?

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()

当前结果

所需散点图图像(相对于边距)

3vpjnl9f

3vpjnl9f1#

  • 主要解决方案是将每个axes的限制设置为(0, 8),并且仅在range(1, 8)上设置tick和ticklables。
  • ax.set(xlim=(0, 8), ylim=(0, 8)).set_ylim(0, 8),在设置刻度/刻度标签并添加右y轴之前,它看起来像plot
  • range(1, 8)[1, 2, 3, 4, 5, 6, 7]
  • 对于axes[0],将xticks、xticklabels和xlabel移到顶部比使用twiny更有效。
  • 如果您仍然想使用axes2x = axes[0].twiny(),请使用axes2x.set_xlim(0, 8)
    *python 3.12.0matplotlib 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()

相关问题