python - 创建自定义绘图
问题描述
我需要创建一个自定义图(见图),其中每个圆圈都是一个变量,它的颜色代表它的值。我需要在变量的值和它的颜色之间有一些相关性,所以如果我改变变量的值,它也会改变它在图中圆圈的颜色。我不知道我在哪里可以学到这个。 https://i.stack.imgur.com/9PnZq.png
解决方案
这是一个根据某些值着色圆圈的示例。该代码创建了 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()
推荐阅读
- c# - C# 和 nodejs 中的 AES 加密
- javascript - jQuery Datatables - 更改和加载 ajax 源后将函数绑定到复选框
- c# - MVC Razor 如何从表单获取选项值并将 viewmodel 属性设置为选定值
- ruby-on-rails - 如何使用 devise-jwt 刷新 JWT 令牌
- java - 在 DGV 中显示 XML 复合元素
- java - 具有不同签名但主体相同的函数
- php - 我们如何在用户使用 sqlite 数据库和 php 从数据库输入期间获得自动完成选项?
- ruby - 改变符号数组
- html - HTML 打印:避免使用行跨度的表格行分页,添加页码
- python - python 2.7 Client Server UDP通信,如何克服丢包?