rainbowtext()函数和y轴实验室

2024-04-20 00:59:56 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,我使用的是彩虹文本函数,可以在here中找到 为了使y轴标签具有与y轴上最接近的conosle名称颜色匹配的颜色。 所以现在我想到了这个代码:

fig, ax= plt.subplots(figsize=(5,6)) #used to take care of the size
sns.barplot(x=gbyplat,y=gbyplat.index, palette='husl') #creating barplot
ax.set_ylabel('Publisher', color='deepskyblue', size=15, alpha=0.8) #setting labels
ax.set_xlabel('Number of titles published', color='slateblue', size=15, alpha=0.7)
ax.set_title('Titles per platform ranking', color='deeppink', size=17, alpha=0.6)
ax.set_xlim(0,2350) #setting limit for the plot
ax.set_xticks(np.arange(0, max(gbyplat), 250)) #ticks frequency
ax.annotate('newest', size=12, xy=(390, 13), xytext=(700, 13.3),
            arrowprops=dict(arrowstyle="fancy")) #annotations on plot
ax.annotate('max', size=9, xy=(2230,0.3), bbox=dict(boxstyle="round", fc="w", alpha=0.5))
ax.plot(2161,0, 'o', color='cyan') #creating the cricle highlight for PS2 max 

p = sns.color_palette("husl", len(gbyplat))
for i, label in enumerate(ax.get_yticklabels()):
    label.set_color(p[i])
rainbow_text(0,5, "Pub lis her".split(),
             [p[10],p[11],p[12]],
             size=10)

但是,问题是我必须手动为新生成的“Publisher”标签设置坐标。根据函数代码,我可以传递ax参数,它会自动将标签匹配到y轴(如果我理解正确的话)。那我怎么做呢?第二个问题,有没有办法访问ylabel坐标(当前y轴标签“Publisher”的坐标)? 谢谢

the plot


Tags: the函数代码alphaforsizeplot颜色
1条回答
网友
1楼 · 发布于 2024-04-20 00:59:56

通过首先绘制ylabel,获取其坐标,然后将其设置为空字符串,可以将文本设置在ylabel通常驻留的位置。然后可以调整example rainbow text函数以使用获得的坐标。你知道吗

它仍然是非常棘手的选择颜色和坐标,这样的文本将有确切的颜色栏旁边。这可能需要大量的试错。你知道吗

enter image description here

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

l =list("ABCDEFGHIJK")
x = np.arange(1,len(l)+1)[::-1]
f, ax=plt.subplots(figsize=(7,4.5))
sns.barplot(x=x,y=l, palette='husl', ax=ax)

plt.xlabel('Number of titles published', color='slateblue', size=15, alpha=0.7)

p = sns.color_palette("husl", len(l))
for i, label in enumerate(ax.get_yticklabels()):
    label.set_color(p[i])


def rainbow_text(x, y, strings, colors, ax=None, **kw):
    if ax is None:
        ax = plt.gca()
    canvas = ax.figure.canvas

    lab = ax.set_ylabel("".join(strings))
    canvas.draw()
    labex = lab.get_window_extent()
    t = ax.transAxes
    labex_data = t.inverted().transform((labex.x0, labex.y0- labex.height/2.))
    ax.set_ylabel("")

    for s, c in zip(strings, colors):
        text = ax.text(labex_data[0]+x, labex_data[1]+y, s, color=c, transform=t,
                       rotation=90, va='bottom', ha='center', **kw)
        text.draw(canvas.get_renderer())
        ex = text.get_window_extent()
        t = transforms.offset_copy(text._transform, y=ex.height, units='dots')

rainbow_text(0, 0.06, ["Pub", "lish", "er"],[p[6], p[5],p[4]],size=15)

plt.show()

相关问题 更多 >