Python matplotlib : Add legend for a colormap

标签 python matplotlib

我是 matplotlib 的新手,我正在尝试重新创建一个如下图所示的对数对数图:

enter image description here

我知道我必须使用颜色图根据我的 x 和 y 值创建这样的输出。我想不通的是如何添加图例,以便它可以动态计算颜色图变量的值(例如,此处称为“Degree”)。到目前为止,这是我得到的示例图:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()

任何帮助将不胜感激。

最佳答案

您可以为绘图分配适当的颜色图,在本例中为灰度颜色图:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [item / 255.0 for item in y]
grayscale_map = plt.get_cmap('gray')

plt.figure()
plt.scatter(x, y, s = 500, c = color, cmap = grayscale_map)
plt.colorbar()
plt.show()

enter image description here

请注意,我将您的 color 列表更改为(大概)范围从 0 到 1 的 float 列表。

关于Python matplotlib : Add legend for a colormap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35444858/

相关文章:

python - 计算存储在列表中的二维 numpy 数组的平均值

python - 如何在Python中的字典中拥有两个键和一个值

python - 如何返回 numpy 数组的列主迭代器?

python - 获取轴的纵横比

python - 检查 Pandas DataFrame 列中的字符串是否在字符串列表中

python - 在 PyQt5 中将数据从子窗口发送到父窗口

python - 在 matplotlib 中绘制 Pandas 日期

python - matplotlib 中的慢速 Line2D 渲染

python - 在 Python 中迭代列以获取单独的图

Python3 : matplotlib. pyplot.plot_date() 日期标签溢出