【问题标题】:Scatter Plot with Conditions带条件的散点图
【发布时间】:2019-05-11 07:21:31
【问题描述】:

假设我有一个数据框

name = ['A', 'B', 'C'] 
score = [2,4,6] 

我想创建一个具有以下条件的散点图,如果分数大于 3,则将气泡着色为绿色,否则将其着色为红色。我还想用相应的名称标记气泡。

我只能使用具有相应名称的气泡创建散点图。

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    您可以使用列表推导为每个score 创建一个颜色列表,并使用scatter()c 参数设置绘图内的颜色。

    要标记气泡,您可以在轴上使用annotate(),请参见下面的示例。

    import matplotlib.pyplot as plt
    
    name = ['A', 'B', 'C'] 
    score = [2,4,6] 
    
    # Set color for every score
    color = ['green' if x>3 else 'red' for x in score]
    
    # Create scatter plot
    fig, ax = plt.subplots()
    ax.scatter(name, score, c=color)
    
    # Set label for every score inside scatter plot
    for i, n in enumerate(name):
        ax.annotate(n, (n,score[i]))
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2012-09-19
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 2017-08-17
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      相关资源
      最近更新 更多