我的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'])
得到的结果是
虽然上面的图并不完全错误,但我希望 X 轴仅包含 transcode
的三个可能值 [1, 17, 99],而不是整个 [1, 100]范围。
谢谢!
最佳答案
在 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 <=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)
关于python - 在 matplotlib 中根据数值变量绘制分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47269695/