我试图创建一个散点图像所需的图像,但我的代码没有空间之前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()
1条答案
按热度按时间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.0
、matplotlib 3.8.0
中测试