rainbowtext()函数和y轴标签

时间:2017-03-13 17:25:19

标签: python matplotlib seaborn

嘿我使用彩虹文字功能,可以在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

1 个答案:

答案 0 :(得分:0)

通过首先绘制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()