简体   繁体   中英

Python Matplotlib lines in scatter plot

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.

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:

未排序和排序的图

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM