3

So I have a normal scatter plot:

import numpy as np
import matplotlib.pyplot as plt
import random

x = np.random.random_sample((100,))
x = np.sort(x)
y = x + np.sin(np.pi * x)
z = 5 * x

fig = plt.figure()
plot = plt.scatter(x, y, s= 10, c = z, cmap='coolwarm')
fig.colorbar(plot)
plt.grid(True, 'both')
plt.show()

that produces a plot something like this

enter image description here

However, I would really like to add a line to scatter and connect these points. It may sound ridiculous since it is easy to follow the points in given case, but imagine if the data would be more scattered and possibly multiple datasets ...

So my goal is to add a line to the scatter above, but the color of the line should change according to value of 'z', the same way scatter plot does. Is that even possible?

EDIT: The x, y, z provided above is just random data to explain the problem. In reality, you can imagine the points (x, y) coordinates are given from an experiment meaning in general there is no relation between x, y, z or even if it is, it is NOT known upfront.

skrat
  • 648
  • 2
  • 10
  • 27

1 Answers1

0

You can add another scatterplot using np.linspace() function:

import numpy as np
import matplotlib.pyplot as plt
import random

x = np.random.random_sample((100,))
x = np.sort(x)
y = x + np.sin(np.pi * x)
z = 5 * x

fig = plt.figure()
plot = plt.scatter(x, y, s= 10, c = z, cmap='coolwarm')
fig.colorbar(plot)
plt.grid(True, 'both')

# add another scatterplot
x_line = np.linspace(np.min(x), np.max(x), num=1000)
y_line = x_line + np.sin(np.pi * x_line)
z_line = 5 * x_line
plt.scatter(x_line, y_line, c=z_line, s=0.1, cmap='coolwarm')

plt.show()

enter image description here

Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73
  • That's a nice trick, however i believe the solution is not robust enough. Imagine the points (x, y) coordinates are given from an experiment. Your solution assumes a couple of things: Firstly, that `x` is monotnic and secondly that `y` and `z` are a known function of `x`. Which is true in this simplified problem I posted with random data, but I was looking for a solution to more general case. I believe your solution fails as soon as `x`is no longer monotonic. – skrat Jun 11 '19 at 08:41
  • @skrat Sort the values by increasing `x` before plotting the line? – Leporello Jun 12 '19 at 09:21