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()
axes
as(0, 8)
, and only set ticks and ticklables onrange(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]
axes[0]
it's more efficient to move the xticks, xticklabels, and xlabel to the top, instead of usingtwiny
.axes2x = axes[0].twiny()
, then useaxes2x.set_xlim(0, 8)
.python 3.12.0
,matplotlib 3.8.0