matplotlib 对于非数值数据,按排序顺序显示两个轴

vmjh9lq9  于 2023-06-06  发布在  其他
关注(0)|答案(4)|浏览(150)

如何实现两个轴的正确顺序:

  • a-b-c而不是c-a-b
  • x-y-z而不是y-z-x
import matplotlib.pyplot as plt

categories_x = ["c", "a", "b", "c", "b"]
categories_y = ["y", "z", "y", "x", "z"]

plt.scatter(categories_x, categories_y)
plt.show()

SO上有很多解决方案,它们依赖于以下两个属性之一:
1.数据可以被转换为数字,例如(“1”,“0”,...)->转换为数值
1.只有一个轴的顺序错误->按这个轴对两个数组进行排序(这样做的原因是,轴记号是按第一次出现的顺序排序的)
但对于我的例子来说,这两种解决方案都不起作用。
我正在寻找一个解决方案,关于如何在matplotlib中使用它。我知道,还有其他可能更好的方式来传达同样的信息,或者其他库没有这个问题。

iklwldmw

iklwldmw1#

使用pandas和有序的Categorical怎么样?

ax = plt.subplot()

X = pd.Categorical(categories_x, ordered=True)
Y = pd.Categorical(categories_y, ordered=True)

ax.scatter(X.codes, Y.codes)
ax.set_xticks(range(len(X.categories)), X.categories)
ax.set_yticks(range(len(Y.categories)), Y.categories)

输出:

ua4mk5z4

ua4mk5z42#

我们可以使用sort函数将它们按顺序排列。

import matplotlib.pyplot as plt

categories_x = ["c", "a", "b", "c", "b"]
categories_y = ["y", "z", "y", "x", "z"]

plt.scatter(sorted(categories_x), sorted(categories_y))
plt.show()
6tdlim6h

6tdlim6h3#

你可以用有序的字符串绘制第一个散点图,以正确设置刻度,然后隐藏它(或使用透明颜色)并绘制实际的图表:

import matplotlib.pyplot as plt
   
categories_x = ["c", "a", "b", "c", "b"]
categories_y = ["y", "z", "y", "x", "z"]
    
p1 = plt.scatter(sorted(categories_x),sorted(categories_y),c='#00000000')
# p1.set_visible(False)

plt.scatter(categories_x,categories_y)

plt.show()
  • 如果您有大量的点并且性能成为问题,则可能需要使用sorted(set(categ...)) *
jdzmm42g

jdzmm42g4#

简单地将所有内容转换为数值并使用x和y标记如何

import matplotlib.pyplot as plt

categories_x = ["c", "a", "b", "c", "b"]
categories_y = ["y", "z", "y", "x", "z"]

def axis_to_number(values):
    # this mapping function can be customized 
    return {j:i for i, j in enumerate(sorted(set(values)))}

map_x = axis_to_number(categories_x)
map_y = axis_to_number(categories_y)

# now convert the original arrays to the 
# mapped values to keep the order
cx = [map_x[i] for i in categories_x]
cy = [map_y[i] for i in categories_y]

xticks, xticklabels = [x for x in map_x.values()], [x for x in map_x.keys()]
yticks, yticklabels = [y for y in map_y.values()], [y for y in map_y.keys()]

# plot
fig, ax = plt.subplots()
ax.plot(cx, cy, 'o')
ax.set_xticks(xticks)
ax.set_xticklabels(xticklabels)
ax.set_yticks(yticks)
ax.set_yticklabels(yticklabels)

相关问题