如何使用matplotlib使用非数值为颜色着色?

时间:2012-05-23 08:59:51

标签: python colors plot matplotlib

我正在尝试使用matplotlib绘制值,我有几个不同类别的点来绘制。实施例

Number   class     x     y 
1        wood      0.2   9.4
3        glass     7.6   4.6

我如何才能优雅地在不同颜色的情节中代表那些不同的类?

1 个答案:

答案 0 :(得分:0)

如果您有不同类别的数据,则可以使用classes

import matplotlib.pyplot as plt

class DataSet(object):
    def __init__(self, name, x_data, y_data, size, color):
        self.name = name
        self.x_data = x_data
        self.y_data = y_data
        self.size = size
        self.color = color

wood = DataSet('wood', [1,2,3,4], [5,7,4,1], 300, 'red')
glass = DataSet('glass', [0,2,0,4], [2,7,4,1], 100, 'blue')
paper = DataSet('paper', [1,7,3,6], [9,9,1,9], 500, '#a5a5a5')
plastic = DataSet('plastic', [3,2,5,5], [1,5,1,8], 700, 'yellow')

categories = [wood, glass, paper, plastic]
#Here we plot all the data:
for cat in categories:
    plt.scatter(cat.x_data, cat.y_data, s=cat.size , color=cat.color, label=cat.name)

plt.legend(loc='lower right', scatterpoints=1)
plt.show()

这给了我们:

enter image description here

哪个可能优雅,也可能不优雅!