Randomize Randomize - 7 months ago 46
Python Question

How to change marker and color in matplotlib for a specific column value?

I have a data file including 3 columns. The first 2 columns represent coordinates, the third one is a string value like 'foo', 'bar' or 'ter'.

I would like to display with python's matplotlib based on this label, different marker and color. Example:


  • foo => red circle

  • bar => green triangle

  • ter => black square



What I did till now is:

import numpy as np
import matplotlib.pyplot as plt

coordData = np.genfromtxt("mydata.csv", usecols=(0,1), delimiter=",", dtype=None)
coordLabels = np.genfromtxt("mydata.csv", usecols=2, delimiter=",", dtype=None)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(coordData[:, 0], coordData[:, 1], c="r", marker="o")
plt.show()


How can I switch marker and color based on the
coordLabels
values?

SOLUTION

Based on the suggestion I made some changes:

coordData = np.genfromtxt("mydata.csv", usecols=(0, 1), delimiter=",", dtype=None)
coordLabels = np.genfromtxt("mydata.csv", usecols=2, delimiter=",", dtype=None)

fig = plt.figure()
ax = fig.add_subplot(111)

uniqueVals = np.unique(coordLabels)

markers = ['^', 'o', '*']
colors = { '^' : 'r',
'o' : 'b',
'*' : 'g'}

for marker, val in zip(markers, uniqueVals):
toUse = coordLabels == val
ax.scatter(coordData[toUse,0], coordData[toUse,1], c = colors[marker], marker=marker)

plt.show()

Answer

If you want the color to be dependent upon the label in coordLabels, you want to set the color equal to that variable instead of 'r' like you have.

ax.scatter(coordData[:, 0], coordData[:, 1], c=coordLabels, marker="o") 

If you want different markers for each of the plots, you will need to create multiple scatter plots (one for each value in coordLabels

uniqueVals = ['foo', 'bar', 'ter']

# Create your own list of markers here (needs to be the same size as `uniqueVals`)
markers = ['o', '^', 's']
colors = ['r', 'g', 'b']

for color, marker, val in zip(colors, markers, uniqueVals):
    toUse = coordLabels == val
    ax.scatter(coordData[toUse,0], coordData[toUse,1], c=color, marker=marker)
Comments