Matplotlib 按字符串列表排列数据以按顺序获取标签(在 ax 上而不是 plt 上)

Matplotlib arranging data by a list of strings to get labels in order (on an ax not a plt)

我的使用需要 AX 功能而不是 PLT(我发现大多数答案都集中在 PLT 上,它没有相同的方法调用)

我正在寻找的是能够组织 x 值... A) 按A、B、C、D、E、F顺序 B) 显示 A 和 C,尽管它们没有与之关联的数据点

我确定它很简单,我错过了...这是一个测试示例

import matplotlib.pyplot as plt

#desired x axis labels    
x_label_order = ["A","B","C","D","E","F"]

#data to be plotted
x=["B","E","D","F"]
y=[1,2,3,4]

#creates graph    
fig, ax = plt.subplots (1,1)
ax.scatter(x,y)

#assuming this is where changes need to be made?
ax.set_xticks(x_label_order)
ax.set_xticklabels(x_label_order)


plt.show()

欢迎来到 Stack Overflow。

对于散点图,通常 xy 都是数值。但是 matplotlib 足够聪明(或不够聪明)将字符串标签自动转换为 运行 数字。

如果要保留序列,在绘图的时候,需要先将x转换到它对应的索引位置:

x_label_order = ["A","B","C","D","E","F"]
x = ["B","E","D","F"]
x = [x_label_order.index(group) for group in x]

然后绘制后,在数字位置设置xticks,并将标签传递给它:

ax.set_xticks(list(range(len(x_label_order))))
ax.set_xticklabels(x_label_order)

你应该得到你需要的东西: