【问题标题】:sorting labels in matplotlib scaterplot在 matplotlib 散点图中排序标签
【发布时间】:2018-11-07 14:26:12
【问题描述】:

我有下面的散点图代码,对应的图如下:

x = ['C9-U2', 'C10-U5', 'C10-U5', 'C11-U1', 'C11-U1']
y = ['J',     'C',      'H',      'J',     'H']
plt.scatter(x,y)

在图中,我希望看到两个轴都已排序,即 x 轴应该是 [C9, C10, C11] (就是这样,因为我已经按该顺序输入了数据),并且y 轴应该是 [C, H, J](不是)。

如何确保两个轴都已排序?

【问题讨论】:

  • 我在问,如何绘制保持两个轴排序的图。我可以通过重新排列数据集来保持任何一个轴排序,但是如何将两个轴排序在一起?
  • 你能在问题中写清楚吗?目前它显示您不关心 x 轴。最好详细描述期望的结果。
  • 我已经更正了代码中的错误,并使问题更加明确。

标签: python-3.x matplotlib


【解决方案1】:

这实际上是一个目前没有好的解决方案的问题。轴单位是根据输入确定的。因此,一种解决方案是手动预先确定分类顺序,先按正确的顺序绘制某些内容,然后再将其删除。

import matplotlib.pyplot as plt

x = ['C9-U2', 'C10-U5', 'C10-U5', 'C11-U1', 'C11-U1']
y = ['J',     'C',      'H',      'J',     'H']

def unitsetter(xunits, yunits, ax=None, sort=True):
    ax = ax or plt.gca()
    if sort:
        xunits = sorted(xunits)
        yunits = sorted(yunits)
    us = plt.plot(xunits, [yunits[0]]*len(xunits),
                  [xunits[0]]*len(yunits), yunits)
    for u in us:
        u.remove()

unitsetter(x,y)
plt.scatter(x,y)

plt.show()

这里,sort 设置为 True,因此您可以在两个轴上获得按字母顺序排序的类别。

如果您有一个希望轴服从的自定义顺序,就像这里的情况(至少对于 x 轴),您需要将该顺序提供给上述函数。

unitsetter(x, sorted(y), sort=False)
plt.scatter(x,y)

【讨论】:

  • 谢谢。但迈克尔的解决方案更简单。
  • 抱歉,Michael 的解决方案似乎不起作用。
  • 您的解决方案有效,但我仍在试图弄清楚它在做什么。同时,寻找更好的解决方案。
  • 如前所述,目前没有更好的解决方案,因为轴单位是在创建时确定的。另一种方法是不绘制字符串,而是绘制数字,然后相应地设置刻度标签。
【解决方案2】:

在“ImportanceOfBeingErnest”之后,代码可以缩短为

# initial plot to set sorted axis label
us = plt.plot(sorted(x),sorted(y))
[u.remove() for u in us]

# now plot the real thing, sorting not required
plt.scatter(x,y)

【讨论】:

    【解决方案3】:

    我改变了你的散点图的创建方式。

    这是我的代码:

    import matplotlib.pyplot as plt
    
    # This is your original code.
    # x = ['C9-U2', 'C10-U5', 'C10-U5', 'C3-U1', 'C3-U1']
    # y = ['J',     'C',      'H',      'J',     'H']
    # plt.scatter(x,y)
    # plt.show()
    
    ordered_pairs = set([
         ('C9-U2', 'J'),
         ('C10-U5', 'C'),
         ('C10-U5', 'H'),
         ('C3-U1', 'J'),
         ('C3-U1', 'H')
    ])
    
    x,y = zip(*ordered_pairs)
    plt.scatter(x, y)
    plt.show()
    

    我将您的数据点转换为有序对的set。这让我们zip 集合,它用于打包和解包每个传递的参数的数组。我们使用* 运算符来逆过程。你可以阅读更多关于ziphere的信息。

    当代码运行时,显示的图像如下,我希望这就是你要找的:

    【讨论】:

    • 虽然您已经对 y 轴进行了排序,但您还没有对 x 轴进行排序。如何保持两个轴排序? (我的代码中有一个错误:用 C11 替换 C3)。
    • 尝试在plt.scatter(x, y) 之后添加plt.yticks(ticks=np.arange(0, 3, 1), labels=['J', 'H', 'C'])(当然还有import numpy as np
    • labels=sorted(set(y)) 更好。您能否将此作为解决方案发布,以便我接受。
    • 不,在您的解决方案中,标签现在显示为已排序,但点仍然保持不变。所以这个解决方案是错误的。
    猜你喜欢
    • 2017-08-24
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2016-09-04
    • 2015-05-09
    • 2013-10-17
    相关资源
    最近更新 更多