温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Creating a custom plot
matplotlib plot python pythonplotter

python - 创建自定义图

发布于 2020-03-30 21:48:28

我需要创建一个自定义绘图(参见图片),其中每个圆圈是一个变量,并且其颜色代表其值。我在变量的值和颜色之间也需要一些相关性,因此,如果我更改变量的值,它也会更改图中圆的颜色。我不知道该在哪里学习。 https://i.stack.imgur.com/9PnZq.png

查看更多

提问者
Davitens
被浏览
93
JohanC 2020-02-02 02:27

这是一个根据一些值绘制彩色圆圈的示例。该代码创建了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情节