python - 在 matplotlib 散点图中自定义 x 和 y 标签

标签 python matplotlib scatter-plot

我有两个长度相等的列表 xsys,用于绘制散点图:

import random
import matplotlib.pyplot as plt

xs = [random.randrange(0,100) for i in range(50)]
ys = [random.randrange(0,100) for i in range(50)]

plt.scatter(xs,ys)

但是,我不需要标准轴标签,而是从中推断出的标签,例如以下词典:

x_labels = { 40 : "First", 52 : "Second", 73: "Third" , 99: "Forth" }
y_labels = { 10 : "FIRST", 80 : "SECOND" }

所以我想做的是绘制一个散点图,其标签为“First”(在 x = 40 处)、“Second”(第二个)在 x = 73 处等等,以及“FIRST”(在 y = 10 处)和y = 80 处的“第二”。不幸的是,我还没有找到实现此目标的方法。

非常感谢!

最佳答案

要在所需位置显示刻度标签,您可以使用:

plt.xticks(list(x_labels.keys()), x_labels.values())
plt.yticks(list(y_labels.keys()), y_labels.values())

正如您所指出的,这会导致坐标不再显示在状态栏中。

显示坐标以及自定义刻度的解决方法是使用 custom tick formattter 。这样的格式化程序有两个参数:一个x值和一个pos。在状态栏中显示坐标时,pos 为 None,但为刻度标签设置。因此,通过检查 pos 而不是 None,格式化程序可以返回所需的标签,否则可以返回格式化为字符串的数字。刻度位置仍然需要通过 plt.xticks() 设置,但标签不需要设置。

这是一个例子:

import random
import matplotlib.pyplot as plt
from matplotlib import ticker

@ticker.FuncFormatter
def major_x_formatter(x, pos):
    if pos is not None:
        return f"{x_labels_list[pos]}"
    x_r = int(round(x))
    if x_r in x_labels:
        return f"{x:.0f}:{x_labels[x_r]}"
    else:
        return f"{x:.2f}"

@ticker.FuncFormatter
def major_y_formatter(y, pos):
    if pos is not None:
        return f"{y_labels_list[pos]}"
    y_r = int(round(y))
    if y_r in y_labels:
        return f"{y:.0f}:{y_labels[y_r]}"
    else:
        return f"{y:.2f}"

xs = [random.randrange(0,100) for i in range(50)]
ys = [random.randrange(0,100) for i in range(50)]

plt.scatter(xs,ys)

x_labels = { 40 : "First", 52 : "Second", 73: "Third" , 99: "Forth" }
x_labels_list = list(x_labels.values())
y_labels = { 10 : "FIRST", 80 : "SECOND" }
y_labels_list = list(y_labels.values())
plt.xticks(list(x_labels.keys()))
plt.yticks(list(y_labels.keys()))
plt.gca().xaxis.set_major_formatter(major_x_formatter)
plt.gca().yaxis.set_major_formatter(major_y_formatter)

plt.show()

resulting plot

关于python - 在 matplotlib 散点图中自定义 x 和 y 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60789695/

相关文章:

python - 如何转换 pandas 数据框

python - 如何处理与 argparse 相关的命令行参数?

python - 设置默认透明度 savefig

javascript - 如何根据值打印不同的路径颜色?

python - 更新 python 动画时删除先前的散点图

python - subprocess.Popen 创建标志

python - Pandas group by 和 sum,但在超过一定数量时创建一个新行

python - Pandas 条形图 : Add marker to distinguish 0 and NaN

python - 在 matplotlib 中手动绘制对数间隔的刻度线和标签

iphone - 如何使用核心图更改部分散点图的线条颜色?