【问题标题】:How do i color a plot using non-numerical values using matplotlib?如何使用 matplotlib 使用非数值为绘图着色?
【发布时间】:2012-05-23 08:59:50
【问题描述】:

我正在尝试使用 matplotlib 绘制值,并且我有几个不同类别的点要绘制。示例

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

我怎样才能优雅地用不同的颜色表示图中的那些不同的类?

【问题讨论】:

    标签: python colors plot matplotlib


    【解决方案1】:

    如果您有不同类别的数据,您可以使用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()
    

    这给了我们:

    这可能是优雅的,也可能不是优雅的!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多