【问题标题】:Scatterplot using different colors for different categories针对不同类别使用不同颜色的散点图
【发布时间】:2019-12-23 17:35:37
【问题描述】:

我想用“x”、“y”、“type”列(以及其他列和数千行)散点图一个 pandas DataFrame,其中 x、y 是浮点数,“type”是一个字符串,即例如,“梨”、“苹果”或“香蕉”。我想根据类型在 (x, y) 处用颜色绘制一个点。

我试过了:

df.plot.scatter(x='x', y='y', c='type', colormap=cmap)

有类似的定义

cmap = colormap_from_dict({ 'pear': 'red', 'apple': 'blue', 'banana': 'yellow' })

但我找不到这样的函数“colormap_from_dict”...你有解决方案吗?谢谢。


作为记录,DataFrame 如下所示:

df = pd.DataFrame([[1, 2, 'banana'], [2, 1, 'apple'], [3, 3, 'pear']], columns=['x', 'y', 'type'])

【问题讨论】:

    标签: python pandas matplotlib scatter-plot


    【解决方案1】:

    您可以通过 lambda 函数应用颜色。

    试试这个:

    from matplotlib import pyplot as plt
    import pandas as pd
    
    df = pd.DataFrame([[1, 2, 'banana'], [2, 1, 'apple'], [3, 3, 'pear']], columns=['x', 'y', 'type'])
    colors = { 'pear': 'red', 'apple': 'blue', 'banana': 'yellow' }
    
    df.plot.scatter(x='x', y='y', c=df['type'].apply(lambda x: colors[x]))
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2020-09-24
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多