doubleOK
doubleOK

Reputation: 353

Matplotlib - set bars different color depending on where they are located on the x axis

I made a bar plot in matplotlib and would like to change the color of the bars to either green or yellow depending on where they are located on the x-axis. For example, the bars that represent the data with the x values in [5, 6, 8, 9] should be colored in yellow, while all the other bars should be green. How do I do that? Thank you!

Upvotes: 1

Views: 1710

Answers (2)

doubleOK
doubleOK

Reputation: 353

The only issue with the solution above was I that had an inconsistent number of bars on the x axis depending on the plot. I went around it by generating the color array based on my x values. If the value fell within the range that I wanted to color red - I added an 'r' to the list, otherwise I added 'g'. But overall it is exactly what was in the answer by Sasha.

fig2, axs2 = plt.subplots(5, 2)
fig2.suptitle("Plot A")
plt.subplots_adjust(wspace = 0.5, hspace = 0.7)
for j in range (10):
    row = j/2
    col = j % 2
    box_title = box_sorted[j]
    box_x = box_top10[j].keys()
    box_y = box_top10[j].values()
    colors = []
    for x in box_x:
        if x in [5, 6, 8, 9]:
            colors.append('r')
        else:
            colors.append('g')
    axs2[row][col].bar([float(v) for v in box_x], [float(v) for v in box_y], align="center", color = colors)
    axs2[row][col].set_title(box_title, fontsize = 12)
    axs2[row][col].set_xlim ([0, 10.0])
    axs2[row][col].set_ylim ([0, float(max(box_y) + 3)])
    xticks = np.arange(0, 10, 1)
    axs2[row][col].set_xticks(xticks)
    yticks = np.arange(0, (max(box_y) + 5), int((max(box_y) + 6)/6))
    axs2[row][col].set_yticks(yticks)
    axs2[row][col].tick_params(axis='both', which='major', labelsize=8)
    axs2[row][col].set_xlabel("rating", fontsize = 8)
    axs2[row][col].set_ylabel("#p", fontsize = 8)

plt.show()

Upvotes: 0

Sasha
Sasha

Reputation: 1408

First, it would be nice if You posted some code.I suggest that You read the information provided on matplotlib.org to see what are the possible options of a function that you are using. Here is a code example:

import numpy as np
import matplotlib.pyplot as plt
x  = np.arange(10)
xx = x**2
cr = ['g','g','g','g','y','y','y','y','g','g']
fig,ax = plt.subplots()
ax.bar(x,xx,color=cr)
plt.show()

This produces:

enter image description here

Upvotes: 1

Related Questions