Pregunta

Is there a way to influence which points are connected in a scatter plot?

I want a scatter plot where the points which are close together are connected. When I plot with the plot(x,y) command, the line between the points depends on the order of the lists which is not what I want.

¿Fue útil?

Solución

I am taking a hint from the wording of your questions that you have two sets of points x,y that are unordered. When you plot them (not in a scatter plot as @tcaswell points out; this would not connect the dots!), the line connecting the points will therefore follow the order of the points.

If this is the issue you want to solve, it can be done like so:

fig, (ax1, ax2) = plt.subplots(ncols=2)

x = np.random.uniform(0, 1, 10)
y = np.random.uniform(0, 1, 10)

# Plot non-ordered points
ax1.plot(x, y, marker="o", markerfacecolor="r")

# Order points by their x-value
indexs_to_order_by = x.argsort()
x_ordered = x[indexs_to_order_by]
y_ordered = y[indexs_to_order_by]

ax2.plot(x_ordered, y_ordered, marker="o", markerfacecolor="r")

The important point is, if the data you are working with are numpy arrays (if they are lists just call np.array(list)) then argsort returns the indices of the sorted array. Using these indices means we can pairwise sort the two lists and plot in the correct order as shown on the right:

Non-sorted and sorted plots

If I have misinterpreted your questions then I apologise. In that case, please leave a comment and I will try to remove my answer.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top