定义散点图的标记

时间:2018-07-10 12:34:08

标签: matplotlib scatter-plot

我想根据数据中的值在绘图中定义标记。

代码在这里

data = np.loadtxt("data.txt")
x1 = data[:,3]
y1 = data[:,10]
z = data[:,1]
mf = data[:,0]

n_file=len(x1)
mrk=[None]



fig, ax1 = plt.subplots()                   
fig.set_size_inches(18.5/2, 10.5/2)


for i in range(len(x1)):

        if mf[i] ==1:
            mrk={'o'}
        elif mf[i] ==2:
            mrk={'s'}
        elif mf[i] ==3:
            mrk={'*'}
        elif mf[i] ==4:
            mrk={'+'}
        else: 
            mrk={'x'}

        sc=plt.scatter(x1[i],y1[i], marker=mrk)


plt.show()

,它返回: TypeError:无法散列的类型:'set'

谢谢

1 个答案:

答案 0 :(得分:2)

似乎没有任何理由在这里使用集合。只需使用字符串即可,即不要使用mrk={'o'}来使用mrk='o'

此外,如果知道mf中的可能值,当然可以使用字典来定义映射。

mapping = {1 : "o", 2 : "s", 3 : "*", 4 : "+", 5 : "x"}

for i in range(len(x1)):
    sc=plt.scatter(x1[i],y1[i], marker=mapping[mf[i]])

编辑

实际上,您可以使用KeyError方法或使用dict.get()来解决defaultdict问题。在下面的示例中,同时使用了两种可能性,其中标记'.'作为默认标记:

from matplotlib import pyplot as plt
import numpy as np
from collections import defaultdict

x1 = np.random.random(100)
y1 = np.random.random(100)
mf = np.random.choice(np.arange(10),100)

fig, axes = plt.subplots(ncols=2)

##using the 'dict.get()' method
mapping1 = {1 : "o", 2 : "s", 3 : "*", 4 : "+", 5 : "x"}
for i in range(len(x1)):
    sc=axes[0].scatter(x1[i],y1[i], marker=mapping1.get(mf[i],'.'))

##using a defaultdict
mapping2=defaultdict(lambda: '.', mapping1)
for i in range(len(x1)):
    sc=axes[1].scatter(x1[i],y1[i], marker=mapping2[mf[i]])

plt.show()

结果确实相同:

result of the code in the edit

相关问题