Change the color of the graph depending on the density (stored in the array) in the line graph in matplotlib

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

But I do not need a scatter plot, I need points that need to be connected, i.e. I need a plot line. Can this be done on a chart?

+4
source share
1 answer

It is not possible to directly connect the points from the scatter plot. But the same effect can be achieved by plotting the lines behind the scattering 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

0
source

Source: https://habr.com/ru/post/1671406/


All Articles