在matplotlib中针对数字变量绘制分类变量

发布于 2021-01-29 15:04:01

我的DataFrame的结构

trx.columns
Index(['dest', 'orig', 'timestamp', 'transcode', 'amount'], dtype='object')

我正在尝试绘制transcode(交易代码),amount以查看每笔交易花费了多少钱。我确保将其转换transcode为如下所示的分类类型。

trx['transcode']
...
Name: transcode, Length: 21893, dtype: category
Categories (3, int64): [1, 17, 99]

我从中得到的结果plt.scatter(trx['transcode'], trx['amount'])

散点图

尽管上面的图并不完全错误,但我希望X轴仅包含transcode[1,17,99]的三个可能值,而不是整个[1,100]范围。

谢谢!

关注者
0
被浏览
112
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    在matplotlib 2.1中,您可以使用字符串来绘制分类变量。即,如果将x值的列提供为字符串,它将把它们识别为类别。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({"x" : np.random.choice([1,17,99], size=100),
                       "y" : np.random.rand(100)*100})
    
    plt.scatter(df["x"].astype(str), df["y"])
    plt.margins(x=0.5)
    plt.show()
    

    在此处输入图片说明

    为了在matplotlib <= 2.0中获得相同的结果,将针对某个索引进行绘制。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({"x" : np.random.choice([1,17,99], size=100),
                       "y" : np.random.rand(100)*100})
    
    u, inv = np.unique(df["x"], return_inverse=True) 
    plt.scatter(inv, df["y"])
    plt.xticks(range(len(u)),u)
    plt.margins(x=0.5)
    plt.show()
    

    使用seaborn可以得到相同的图stripplot

    sns.stripplot(x="x", y="y", data=df)
    

    可以通过seaborn的来完成更好的表示swarmplot

    sns.swarmplot(x="x", y="y", data=df)
    

    在此处输入图片说明



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看