dad
dad

Reputation: 25

Python Pandas Bar Chart - change color for specific bars

I have some data in csv.

It has only one column and contents strings with soccer scores like "0:0","1:2",etc.

Then I building histogam with df[0].value_counts().plot(kind='bar').

What is the best way to change color only for bars with "draw" score (0:0, 1:1,...)?

I can add second column with '1' for draws and '0' for others, but don't understand how to use it as bar color.

I tried solution from another question here

df[0].value_counts().plot(kind='bar', color=(df[1] == 1).map({True: 'orange', False: 'blue'})) but got wrong coloring

wrong coloring, expecting orange "1:1"
example dataframe:

      0  1
0   2:0  0
1   2:3  0
2   1:1  1
3   1:3  0
4   2:0  0
5   3:4  0
6   1:2  0
7   0:1  0
8   2:3  0
9   0:1  0
10  1:1  1
11  2:1  0
12  0:1  0
13  1:2  0
14  0:3  0

Upvotes: 2

Views: 1741

Answers (1)

jezrael
jezrael

Reputation: 862611

Use numpy.where for test if match 1 column with Index.isin for array of colors passed to color parameter:

a = df[0].value_counts()
colors = np.where(a.index.isin(df.loc[df[1] == 1, 0].unique()), 'orange', 'blue')
a.plot(kind='bar', color=colors)

g

Upvotes: 2

Related Questions