在matplotlib中控制散点图y轴顺序

时间:2020-07-06 10:46:11

标签: python pandas matplotlib

我试图控制matplotlib散点图上的y轴顺序,但是我拥有的数据中x轴和y轴的顺序导致该图显​​示不正确。

这里有一些代码来说明问题,并且是试图解决问题的次佳尝试。

import pandas as pd
from numpy import random
import matplotlib.pyplot as plt

# make some fake data
axes = ['a', 'b', 'c', 'd']
pairs = pd.DataFrame([(x, y) for x in axes for y in axes], columns=['x', 'y'])
pairs['value'] = random.randint(100, size=16) + 100
# remove the diagonal
pairs_nodiag = pairs[pairs['x'] != pairs['y']]
# zero the values for the diagonal
pairs_diag = pairs.copy()
pairs_diag.loc[pairs_diag['x'] == pairs_diag['y'], 'value'] = 0

fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(5, 3))
scatter = ax[0].scatter(x=pairs['x'], y=pairs['y'], s=pairs['value'])
scatter = ax[1].scatter(x=pairs_nodiag['x'], y=pairs_nodiag['y'], s=pairs_nodiag['value'])
scatter = ax[2].scatter(x=pairs_diag['x'], y=pairs_diag['y'], s=pairs_diag['value'])

plt.show()

3 plots

最左边的是原始数据。中间是有问题的情节。我希望y轴与最左边的图相同。最右边的图是我使用次优解决方法后的情况。我敢肯定有一种方法可以控制轴上的顺序,但是我对Python的了解还不够,还不知道该怎么做。

1 个答案:

答案 0 :(得分:3)

您需要使用所需的映射来创建自己的StringCategoryConverter(默认情况下,matplotlib将字符串映射到出现的顺序中的数字)。

import matplotlib.category as mcat

# insert the following before scatter = ax[1].scatter(...
units = mcat.UnitData(sorted(pairs_nodiag.y.unique()))
ax[1].yaxis.set_units(units)
ax[1].yaxis.set_major_locator(mcat.StrCategoryLocator(units._mapping))
ax[1].yaxis.set_major_formatter(mcat.StrCategoryFormatter(units._mapping))

enter image description here


更新:以下是不使用_mapping的官方方法:

import matplotlib

# insert the following before scatter = ax[1].scatter(...
scc = matplotlib.category.StrCategoryConverter()
units = scc.default_units(sorted(pairs_nodiag.y.unique()), ax[1].yaxis)
axisinfo = scc.axisinfo(units, ax[1].yaxis)
ax[1].yaxis.set_major_locator(axisinfo.majloc)
ax[1].yaxis.set_major_formatter(axisinfo.majfmt)