wolfreekpotter
wolfreekpotter

Reputation: 3

define marker for scatter plot

I want to define markers in my plot based on the values in my data.

the code is here

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()

and it returns: TypeError: unhashable type: 'set'

Thanks

Upvotes: 0

Views: 404

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339630

There does not seem to be any reason to use a set here. Just use strings, i.e. instead of mrk={'o'} use mrk='o'.

In addition, you may of course use a dictionary to define your mapping, in case the possible values in mf are known.

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]])

EDIT:

You actually can get around the KeyError problem by either using the dict.get() method or by using a defaultdict. Below an example that utilises both possibilities with '.' as default for the marker:

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()

The results are indeed identical:

result of the code in the edit

Upvotes: 2

Related Questions