Scatter plots in Pandas/Pyplot: How to plot by category

前端 未结 8 1005
孤城傲影
孤城傲影 2020-11-22 10:53

I am trying to make a simple scatter plot in pyplot using a Pandas DataFrame object, but want an efficient way of plotting two variables but have the symbols dictated by a t

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:58

    You can use df.plot.scatter, and pass an array to c= argument defining the color of each point:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
    df['key1'] = (4,4,4,6,6,6,8,8,8,8)
    colors = np.where(df["key1"]==4,'r','-')
    colors[df["key1"]==6] = 'g'
    colors[df["key1"]==8] = 'b'
    print(colors)
    df.plot.scatter(x="one",y="two",c=colors)
    plt.show()
    

提交回复
热议问题