python - 使用列表为 matplotlib 中的系列分配颜色?

标签 python matplotlib graph plot colors

我认为制作具有 N 个不同系列的散点图(如 Excel 中的散点图)的最简单方法是有 3 个列表:i) x_coordinates 将有 N 个包含 X 位置的列表; ii) y_coordinates 也将有 N 个包含 Y 位置的列表; iii) color_map 将有 N 个元素,其中包含每个系列的不同 RGB 颜色。

我的问题是绘制标记颜色时的顺序变得很奇怪。为什么会发生这种情况以及如何解决它?

import matplotlib.pyplot as plt
import random
x_coordinates = [(range(1,4))]*2
y_coordinates = [[3,4,5],[2,2,2]]
color_map = []
for i in range(0,len(x_coordinates)):
    r = lambda: random.randint(0,255)
    rgb_hex = ('#%02X%02X%02X' % (r(),r(),r()))
    color_map.append(rgb_hex)
plt.scatter(x_coordinates,y_coordinates,c=color_map)
plt.show()

x/y 坐标和颜色列表

[[1, 2, 3], [1, 2, 3]] #x
[[3, 4, 5], [2, 2, 2]] #y
['#E6764F', '#A12678'] #colors

enter image description here

最佳答案

我认为基本的问题是你必须重新考虑是否真的需要scatter函数。从您发布的内容来看,我认为重复使用 plot 就足够了。 scatter 生成一系列彩色标记(可以为标记分配不同的颜色和大小),而 plot 仅用单一颜色绘制线条。但是,这些线也可以在点处有标记(使用单一颜色)。因此,解决这个问题的方法是为每个系列创建一个线图。 (如果你不想要这条线,你可以将linestyle设置为'none'。但是wrt your previous question我相信你无论如何都想这样做)

注意:我还在您的代码中应用了一些修饰:1)无需为颜色创建十六进制字符串。只需使用具有 3 个从 0 到 1 缩放的元素的列表/元组。 2) 您可以简单地将随机函数保存到 r 中。无需创建 lambda 函数。

import matplotlib.pyplot as plt
import random

# x and y coordinates
x_coordinates = [range(1,4)]*2
y_coordinates = [[3,4,5],[2,2,2]]

# colors (one per series --> 2 in this example)
colors = []
r = random.random
for i in range(0,len(x_coordinates)):
    rgb =  (r(),r(),r())
    colors.append(rgb)

# iterate over the series
for x, y, c in zip(x_coordinates, y_coordinates, colors):
    plt.plot(x, y, color=c, linestyle='-', marker='o', markeredgecolor='k',
            markersize=10)

# show the figure
plt.margins(x=0.1, y=0.1)
plt.show()

结果: enter image description here

关于python - 使用列表为 matplotlib 中的系列分配颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31374759/

相关文章:

python - Python 中是反射增广加法 (__iadd__) 吗?

python - 处理 "StanfordTokenizer will be deprecated in version 3.2.5"警告

python - 多索引 Seaborn 线图

python - 从集合中查找断开连接的图的算法

java - 我的代码没有显示图的邻接列表

algorithm - 恢复时间最短的路径

python - 最近对 Python 执行模型的更改?

Python 正则表达式 "object has no attribute"

python - 子集维恩图 - 即嵌入整个集合的维恩图

python - 图例的“最佳”位置是覆盖文本