【问题标题】:Plotting categorical variable against numeric variable in matplotlib在 matplotlib 中根据数值变量绘制分类变量
【发布时间】:2023-03-26 15:10:01
【问题描述】:

我的 DataFrame 的结构

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

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

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

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

Scatter plot

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

谢谢!

【问题讨论】:

  • 查看箱线图、小提琴图或条形图。

标签: python pandas matplotlib


【解决方案1】:

在 matplotlib 2.1 中,您可以使用字符串绘制分类变量。 IE。如果您将 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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-14
    • 2020-05-08
    • 2017-01-05
    • 1970-01-01
    • 2015-10-16
    • 2019-04-14
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多