Home > OS >  Matplotlib change colour of every second element in yaxis
Matplotlib change colour of every second element in yaxis

Time:03-20

So I have this plot here: plot

What I want to do is to have every second element of yaxis to be coloured for example in blue and the rest in red.

Here is the result I want to get: desired result

and here is the code I got:

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

mpl.rcParams['toolbar'] = 'None'
plt.style.use('fivethirtyeight')

result_7_s = amount * s_7_days
result_14_s = amount * s_14_days
result_21_s = amount * s_21_days
result_7_fc = amount * fc_7_days
result_14_fc = amount * fc_14_days
result_21_fc = amount * fc_21_days
final_y = np.array([int(result_7_s), int(result_14_s), 
                    int(result_21_s), int(result_7_fc), 
                    int(result_14_fc), int(result_21_fc)])

fig, ax = plt.subplots(num = 'Test')
x = np.array([7, 14, 21])
plt.xticks(ticks = x, labels = x)
plt.yticks(ticks = final_y, labels = final_y)
plt.title(f'Prices for {amount} people')
plt.xlabel('Days')
plt.ylabel('Price')
plt.tight_layout()
ax.bar(x - 0.5, final_y[:3], width=1, color='#444444', label='Standard')
ax.bar(x   0.5, final_y[3:], width=1, color='#e5ae38', label='First Class')
ax.tick_params(axis='y', colors = 'blue')  # <-------
ax.yaxis.set_major_formatter('{x}$')

plt.legend()
plt.savefig('result.png')
plt.show()

CodePudding user response:

Iterate over the tick labels to apply the desired color to each one of them:

for n, tick_label in enumerate(ax.yaxis.get_ticklabels()):
    tick_label.set_color("red" if n%2 else "blue")

CodePudding user response:

Here is the solution I came with:

for i in range(0, 3):
    plt.gca().get_yticklabels()[i].set_color('blue')
    
for i in range(3, 6):
    plt.gca().get_yticklabels()[i].set_color('red')
  • Related