【问题标题】:Control scatter plot y axis order in matplotlib在matplotlib中控制散点图y轴顺序
【发布时间】:2020-07-06 10:46:11
【问题描述】:

我正在尝试控制 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 方面还不够专业,还不知道如何做到这一点。

【问题讨论】:

  • 我认为您的解决方法不是解决方法,但它是正确的方法。通过布尔索引,您可以正确地将 ('a', 'b') 作为第一个值,但这当然会破坏顺序。
  • 我认为这是一种有效的解决方法,但实际上,我得到的数据并不完整,因此必须对其进行修补以确保绘图正常工作会很烦人。
  • 不幸的是,我认为您必须为不想绘制的值保留一些占位符。我会使用 None 而不是 0
  • @AndrewChisholm:感谢您的提问。点赞!

标签: python pandas matplotlib


【解决方案1】:

您需要使用所需的映射创建自己的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))


更新:以下是不使用_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)

【讨论】:

  • @Stef:谢谢。今天学到了新的matplotlib.category 来排序轴。点赞!删除了我的答案,因为它不再相关。
猜你喜欢
  • 1970-01-01
  • 2016-11-10
  • 2014-09-18
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多