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

Python 在matplotlib中控制散点图y轴顺序,python,pandas,matplotlib,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 f

我试图控制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()


最左边是原始数据。中间是有问题的情节;我希望y轴与最左边的绘图相同。最右边的情节是我使用次优解决方案后的状态。我确信有一种方法可以控制轴上的顺序,但我对Python还不够精通,不知道如何做到这一点。

您需要使用所需的映射创建自己的映射(默认情况下,matplotlib将字符串映射到发生序列中的数字)


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

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)

我认为你的变通方法不是变通方法,但它是正确的方法。使用布尔索引可以正确地将('a','b')作为第一个值,但这当然会打乱顺序。我认为这是一个有效的解决方法,但实际上,我得到的数据不完整,因此必须修补它以确保绘图工作会很烦人。不幸的是,我认为您必须为不希望绘图的值保留一些占位符。我会使用
None
而不是0@AndrewChisholm:谢谢你的提问。向上投票@谢谢。今天学习了新的
matplotlib.category
对axis进行排序。向上投票!删除了我的答案,因为它不再相关。
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)