【问题标题】:How to change marker and color in matplotlib for a specific column value?如何更改 matplotlib 中特定列值的标记和颜色?
【发布时间】:2016-04-17 02:37:21
【问题描述】:

我有一个包含 3 列的数据文件。前 2 列代表坐标,第三列是字符串值,例如 'foo'、'bar' 或 'ter'。

我想根据这个标签、不同的标记和颜色用 python 的 matplotlib 显示。示例:

  • foo => 红圈
  • 条形 => 绿色三角形
  • ter => 黑色方块

到目前为止我所做的是:

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

如何根据coordLabels 值切换标记和颜色?

解决方案

根据建议我做了一些更改:

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    如果您希望颜色依赖于 coordLabels 中的标签,您希望将颜色设置为等于 那个 变量,而不是像您一样使用 'r'

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

    如果您想为每个图使用不同的标记,则需要创建多个散点图(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)
    

    【讨论】:

    • 经过一些更改,我已经适应了您的建议。谢谢。
    猜你喜欢
    • 2018-07-08
    • 2012-08-26
    • 1970-01-01
    • 2013-09-08
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多