Warm tip: This article is reproduced from stackoverflow.com, please click
matplotlib plot python pythonplotter

Creating a custom plot

发布于 2020-03-30 21:15:51

I need to create a custom plot (see image) where each circle is a variable and it's color represents the value of it. I need too some correlation between the value of the variable and it's color, so if i change the value of the variable it also changes the color of it's circle in the plot. I don't have no idea where can I learn this. https://i.stack.imgur.com/9PnZq.png

Questioner
Davitens
Viewed
68
JohanC 2020-02-02 02:27

Here is an example of coloring circles depending on some value. The code creates lists of 20 x and y positions, and a list of 20 random values between -1 and 1. Depending on their value, the circles are colored red to yellowish to green.

from matplotlib import pyplot as plt
import random

x = [i // 4 for i in range(20)]
y = [i % 4 for i in range(20)]
z = [random.uniform(-1, 1) for i in range(20)]

# create a scatter plot for the given x,y positions, make them quite large, color them
# using z and the Red-Yellow-Green color map, give them a black border 

plt.scatter(x, y, s=400, c=z, cmap='RdYlGn', ls='-', edgecolors='black')

plt.colorbar() # add a colorbar to show how the values correspond to colors

plt.xlim(-0.9, 4.9) # because of very large scatter dots, the default limits are too narrow
plt.ylim(-0.9, 3.9)

plt.show() # display the plot on the screen

resulting image

Here is a possible approach to draw a 12x4 grid with 3 values:

from matplotlib import pyplot as plt
import random

num_columns = 12
num_rows = 4
num_values = 3
x = [[j for j in range(num_columns)] for i in range(num_rows)]
y = [[i for j in range(num_columns)] for i in range(num_rows)]
z = [[random.randint(1, num_values) for j in range(num_columns)] for i in range(num_rows)]

plt.scatter(x, y, s=400, c=z, cmap='RdYlGn', ls='-', edgecolors='black')

cbar = plt.colorbar(ticks=range(1, num_values + 1))
cbar.ax.set_yticklabels([f'Value {v}' for v in range(1, num_values + 1)])

plt.xlim(-0.5, num_columns - 0.5)
plt.ylim(-0.5, num_rows - 0.5)
plt.xticks(range(num_columns))
plt.yticks(range(num_rows))

plt.show()

12x4 plot