matplotlib 如何将y轴刻度标签数字转换为字母

ykejflvf  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(88)

代码:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

data = list(map(lambda n:str(n), np.random.choice(np.arange(1,50), 1000)))
fig, ax = plt.subplots(1,1)
sns.countplot(y=data,ax=ax)
ax.set_yticklabels(ax.get_yticklabels(), fontsize=5)
plt.show()

我得到了下面的图。y轴是字符串类型的1~2位整数。我想把它们转换成字母,如
1->AL,2->AK,4->AZ,5->AR,.
我尝试使用ax.set_yticks(ylabel, converted ylabel),但它不工作。我该怎么做?

wkftcu5l

wkftcu5l1#

您需要创建一个函数,将数字转换为所需的字母表示形式。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Number to desired letters (can customize this function)
def number_to_letters(n):
    first_letter = chr(64 + (n // 26) + 1)  # 'A' is 65 in ASCII
    second_letter = chr(64 + (n % 26) + 1)

    return first_letter + second_letter

data = list(map(lambda n: str(n), np.random.choice(np.arange(1, 50), 1000)))
# mapping numbers to letters
data_letters = [number_to_letters(int(d)) for d in data]

fig, ax = plt.subplots(1, 1)
sns.countplot(y=data_letters, ax=ax, order=sorted(set(data_letters)))
ax.set_yticklabels(sorted(set(data_letters)), fontsize=5)
plt.show()
e37o9pze

e37o9pze2#

除了@Yuri的答案之外,我还想提出另一个对我也有效的答案。这就是通过get_yticklabels()获取标签(plt.Text对象的列表),并通过plt.Text.get_text()plt.Text.get_position()从中提取信息。

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def number_to_letters(n):
    n = int(n)
    first_letter = chr(64 + (n // 26) + 1)  # 'A' is 65 in ASCII
    second_letter = chr(64 + (n % 26) + 1)
    return first_letter + second_letter
data = list(map(lambda n:str(n), np.random.choice(np.arange(1,50), 1000)))
fig,ax = plt.subplots(1,1)
sns.countplot(y=data,ax=ax)
new_label = []
for t in ax.get_yticklabels():
    txt = number_to_letters(t.get_text())
    loc = t.get_position()
    new_label.append(plt.Text(position=loc,text=txt))
ax.set_yticklabels(new_label,fontsize=5)
plt.show()

相关问题