Home > Back-end >  Is there any way to express changing color from Matplotlib, Python?
Is there any way to express changing color from Matplotlib, Python?

Time:12-22

Before you reading, I apologize about broken English. I have a data array of moving mass, and want to show them by time area. Like:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0, 1, 2, 3])
y = np.array([3, 4, 5, 6])

plt.plot(x,y)

In this code, I just want to see them with different color each rows. For example, point (0,3) is white dot, point (3,5) is black dot, and (1,4) , (2,5) are gray dot but different brightness.

I just started python, so I searched pyplot lib but didn't find examples.

I tried with Seaborn library, and Pyplot 3d examples. But didn't find solution to express what want to do.

CodePudding user response:

Pass a color argument into a scatter function that displays given points and any defined features.

#array declaration
#...

for x1, y1 in zip(x, y):
    if x1 == 0:
        color = "white"
    elif x1 == 1 or x1 == 2:
        color = "gray"
    elif x1 == 3:
        color = "black"
        
    plt.scatter(x1, y1, c=color)

# plot linear line from arrays

We use the zip class to iterate through both arrays at once, allowing us to plot each point from the given arrays. We use the x-coordinates from the x array to determine what color to label the dot. The scatter function puts this point on the graph, giving us options to change features of the given dot(s).

--

The final code would look something like this:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0, 1, 2, 3])
y = np.array([3, 4, 5, 6])

for x1, y1 in zip(x, y):
    if x1 == 0:
        color = "white"
    elif x1 == 1 or x1 == 2:
        color = "gray"
    elif x1 == 3:
        color = "black"
        
    plt.scatter(x1, y1, c=color)

plt.plot(x, y)
plt.show()

Documentation on matplotlib's scatter function can be found Example Output

The c keyword argument tells Matplotlib which colour to use for which point using a grey colourmap. By default, said colourmap goes from black to white, so we pass x reversed. vmin and vmax are the least and greatest values to be assigned colours. Note that the first point is white (hence invisible).

  • Related