Search code examples
pythonmatplotlibplotxticks

Multiple colors of matplotlib single xtick_label


I am fairly new to Matplotlib and appreciate your help with my question:

I am looking to generate a figure that each label has 2 colors. For example, a label named 'first_color\nsecond_color', first and second color are different. If I use label.set_color(colors[0]), the whole color of label will be changed. If I use label.set_color(colors[i % 2]), the color of neighboring label will be different. I just want different color in single internal label.

labels = ['1first_color\nsecond_color', '2first_color\nsecond_color', '3first_color\nsecond_color',
          '4first_color\nsecond_color', '5first_color\nsecond_color']
colors = [sns.color_palette('tab10')[0], sns.color_palette('tab10')[1]]  

plt.plot(range(len(labels)), [0, 1, 2, 3, 4])


plt.xticks(range(len(labels)), labels)
for i, label in enumerate(plt.gca().get_xticklabels()):


    label.set_color(colors[0])    

    #label.set_color(colors[i % 2])

label.set_color(colors[0])

label.set_color(colors[i % 2])

I am sure there is support for such a feature in Matplotlib. I did look through the docs/forums but could not find much help.

Any suggestions will be much appreciated.

I want to know how to set multiple colors at single label.


Solution

  • If the tick labels need a different color on different lines, you can explicit place text at the tick positions. With an x-axis transform, the x-position can be given in "data coordinates" (0 for the first label, 1 for the second, etc.) and the y-position in "axes coordinates" (0 at the bottom, 1 at the top of the "ax", negative values for positions below the "ax"). You may need to change the y-positions a bit, depending on the tick lengths and fonts used.

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    labels = ['1first_color\nsecond_color', '2first_color\nsecond_color', '3first_color\nsecond_color',
              '4first_color\nsecond_color', '5first_color\nsecond_color']
    colors = sns.color_palette('tab10')[:2]
    plt.plot(range(len(labels)), [0, 1, 2, 3, 4])
    plt.xticks(range(len(labels)), []) # set tick positions without labels
    ax = plt.gca()  # get the current subplot
    for i, label in enumerate(labels):
        ax.text(i, -0.03, label.split('\n')[0], color=colors[0],
                transform=ax.get_xaxis_transform(), ha='center', va='top')
        ax.text(i, -0.08, label.split('\n')[1], color=colors[1],
                transform=ax.get_xaxis_transform(), ha='center', va='top')
    plt.tight_layout()
    plt.show()
    

    coloring tick labels with different colors