You're looking to control the exact position of the text relative to the point. This involves adjusting two main parameters in the ax.text() call:
- Offset (
text_offset_x, text_offset_y): These determine the coordinate where the text anchor point will be placed relative to the data point.
- Horizontal Alignment (
ha): This dictates which part of the text string (left edge, center, or right edge) is aligned with the x coordinate you provide.
Let's modify the _update_scatter_and_labels method to achieve text directly to the left of the point with a little gap.
Original (text to top-right):
# In _update_scatter_and_labels
text_offset_x = 0.2
text_offset_y = 0.2
for i, (x, y) in enumerate(updated_data):
label = updated_labels[i]
txt = self.ax.text(x + text_offset_x, y + text_offset_y, str(label),
fontsize=9, color=color, ha='left', va='center')
Modified (text to left):
import matplotlib.pyplot as plt
import numpy as np
class LabeledScatterPlot:
def __init__(self, ax):
self.ax = ax
self.src_scatter = ax.scatter([], [], c='blue', label='Source Points')
self.dst_scatter = ax.scatter([], [], c='red', label='Destination Points')
self.src_texts = []
self.dst_texts = []
self.src_data = np.empty((0, 2))
self.src_labels = []
self.dst_data = np.empty((0, 2))
self.dst_labels = []
ax.set_title("Scatter Plot with Labels")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.grid(True)
ax.legend()
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
def _update_scatter_and_labels(self, scatter_obj, text_list, current_data, current_labels, new_x, new_y, new_labels, color):
for txt in text_list:
txt.remove()
text_list.clear()
updated_data = np.c_[new_x, new_y]
updated_labels = list(new_labels)
scatter_obj.set_offsets(updated_data)
# --- MODIFICATION START ---
# Adjust text position
# For text directly to the left:
# 1. Use a NEGATIVE text_offset_x to move the text anchor point to the left of the data point.
# 2. Set text_offset_y to 0 to keep it vertically aligned with the data point.
# 3. Set ha='right' so the RIGHT edge of the text string aligns with the anchor point.
# This makes the text extend to the left from the anchor point, creating the desired gap.
text_offset_x = -0.2 # Adjust this value for more/less gap
text_offset_y = 0.0 # Align vertically with the point
for i, (x, y) in enumerate(updated_data):
label = updated_labels[i]
txt = self.ax.text(x + text_offset_x, y + text_offset_y, str(label),
fontsize=9, color=color, ha='right', va='center')
text_list.append(txt)
# --- MODIFICATION END ---
current_data = updated_data
current_labels = updated_labels
return current_data, current_labels
def add_src_points(self, x_coords, y_coords, labels, text_color='blue'):
self.src_data, self.src_labels = self._update_scatter_and_labels(
self.src_scatter, self.src_texts,
self.src_data, self.src_labels,
x_coords, y_coords, labels, text_color
)
self.ax.figure.canvas.draw_idle()
def add_dst_points(self, x_coords, y_coords, labels, text_color='red'):
self.dst_data, self.dst_labels = self._update_scatter_and_labels(
self.dst_scatter, self.dst_texts,
self.dst_data, self.dst_labels,
x_coords, y_coords, labels, text_color
)
self.ax.figure.canvas.draw_idle()
def clear_all_points(self):
self.add_src_points([], [], [])
self.add_dst_points([], [], [])
# --- Example Usage ---
if __name__ == "__main__":
fig, ax = plt.subplots(figsize=(8, 6))
plot_manager = LabeledScatterPlot(ax)
# Add initial blue points with labels 1, 2, 3, 4
blue_x = [1, 2, 3, 4]
blue_y = [5, 6, 7, 8]
blue_labels = [1, 2, 3, 4]
plot_manager.add_src_points(blue_x, blue_y, blue_labels, 'darkblue')
# Add initial red points with labels A, B
red_x = [7, 8]
red_y = [2, 3]
red_labels = ['A', 'B']
plot_manager.add_dst_points(red_x, red_y, red_labels, 'darkred')
# Show the plot
plt.show(block=False)
print("\nPress Enter to update blue points...")
input()
new_blue_x = [1.5, 2.5, 5, 6]
new_blue_y = [5.5, 6.5, 2, 3]
new_blue_labels = ['New1', 'New2', 'New3', 'New4']
plot_manager.add_src_points(new_blue_x, new_blue_y, new_blue_labels, 'purple')
plt.draw()
print("Press Enter to add more red points...")
input()
more_red_x = [6, 7, 8, 9]
more_red_y = [1, 2, 3, 4]
more_red_labels = ['R1', 'R2', 'R3', 'R4']
plot_manager.add_dst_points(more_red_x, more_red_y, more_red_labels, 'green')
plt.draw()
print("Press Enter to clear all points...")
input()
plot_manager.clear_all_points()
plt.draw()
plt.show()