4

I have a file with three columns, lets say, x y z. I need to plot x Vs y but I need to change the color of that (x,y) value depending on its density (stored in z column). I understand that I need to use color map and have to map the values of the color with the z array. I can do that via scatter plot as also shown in this post: How can I make a scatter plot colored by density in matplotlib?

But I do not need the scatter plot, I need the points to be connected, ie I need a line plot. Can it be done in line plot?

Community
  • 1
  • 1

1 Answers1

1

It's not possible to connect points from a scatter plot directly. But the same effect can be achieved by plotting a line behind the scatter points.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3,6)
y = np.sin(x)
z = 0.5+np.random.rand(len(x))

fig, ax = plt.subplots()
ax.plot(x, y, color="k", marker=None, zorder=0)
sc = ax.scatter(x, y, c=z, s=100, edgecolor='',zorder=3)
plt.colorbar(sc, label="Density")

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712