首页 > 解决方案 > 创建自定义绘图

问题描述

我需要创建一个自定义图(见图),其中每个圆圈都是一个变量,它的颜色代表它的值。我需要在变量的值和它的颜色之间有一些相关性,所以如果我改变变量的值,它也会改变它在图中圆圈的颜色。我不知道我在哪里可以学到这个。 https://i.stack.imgur.com/9PnZq.png

标签: pythonmatplotlibplotpythonplotter

解决方案


这是一个根据某些值着色圆圈的示例。该代码创建了 20 个 x 和 y 位置的列表,以及 20 个介于 -1 和 1 之间的随机值的列表。根据它们的值,圆圈被着色为红色到淡黄色到绿色。

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

结果图像

这是绘制具有 3 个值的 12x4 网格的可能方法:

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 情节


推荐阅读