Search code examples
pythonmatplotlibcolorsscatter-plotxticks

Color xticks to match color of scatter plot points


Here is my plot: enter image description here

generated from the python code

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(20, 10))
n = 70
x = [f'{i}{val}' for i,val in enumerate(np.arange(n)[::-1])]
y = np.random.randint(50, 100, n)
scatter_colors = np.random.rand(n)

plt.scatter(x, y, c=scatter_colors)
plt.xticks(rotation=90, ha='right')
plt.show()

Any ideas on how to make the ticks labels have the same color as the plotted points?
Adding c=scatter_colors or color=scatter_colors to the plt.xticks(rotation=90, ha='right') throws a value error.
The data is gibberish and just minimum to reproduce what I want.


Solution

  • Here's an approach (rewritten using the object-oriented interface) using Axes.get_xticklabels and Text.set_color:

    fig, ax = plt.subplots(figsize=(20, 10))
    n = 70
    x = [f'{i}{val}' for i,val in enumerate(np.arange(n)[::-1])]
    y = np.random.randint(50, 100, n)
    
    scatter_colors = np.random.rand(n)
    viridis = plt.get_cmap('viridis')
    
    ax.scatter(x, y, c=scatter_colors)
    ax.set_xticks(np.arange(n), x, ha='right', rotation=90)
    
    for color, label in zip(scatter_colors, ax.get_xticklabels()):
        label.set_color(viridis(color))
    plt.show()
    

    Output:

    enter image description here

    Also doable with the pyplot interface:

    plt.figure(figsize=(20, 10))
    n = 70
    x = [f'{i}{val}' for i,val in enumerate(np.arange(n)[::-1])]
    y = np.random.randint(50, 100, n)
    
    scatter_colors = np.random.rand(n)
    viridis = plt.get_cmap('viridis')
    
    plt.scatter(x, y, c=scatter_colors)
    plt.xticks(rotation=90, ha='right')
    
    for color, label in zip(scatter_colors, plt.xticks()[1]):
        label.set_color(viridis(color))
    plt.show()