0

I have a bar plot from a pandas DataFrame with one column:

import pandas as pd
import matplotlib.pyplot as plt


columns = ["Foo"]
data = [50, 201, 279]
index=["Item 1", "Item 2", "Item 3"]
df = pd.DataFrame(data=data, index=index, columns=columns)

which looks like the following:

        Foo
Item 1   50
Item 2  201
Item 3  279

And if I plot it using pandas plotting interface:

ax = df.plot(kind="barh", color="#00576B", rot=0, legend=False, align='center', width=0.5)
ax.set_title("My title")
ax.set_ylabel("")
ax.set_xlabel("My label in foo")
ax.grid(True)
ax.set_axisbelow(True)
plt.show()

this yields the following plot: enter image description here

How can I now change the colors of single bars using pandas plotting interface without changing the DataFrame structure or changing to matplotlib's interface?

Note: I know that passing colors using colors=["color1", "color2", ..] works when transposing the DataFrames index into columns as described here but this destroys the plotting layout e.g. the spaces between the bars. So I am looking for a direct solution using pandas' plotting interface and less code.

Cord Kaldemeyer
  • 6,405
  • 8
  • 51
  • 81

1 Answers1

2

This might not be the most elegant way, but you can always loop over matplotlib patches and change their colors invidividually:

ax = df.plot(kind="barh", color="#00576B", rot=0, legend=False, align='center', width=0.5)
ax.set_title("My title")
ax.set_ylabel("")
ax.set_xlabel("My label in foo")
ax.grid(True)
ax.set_axisbelow(True)
# loop over patches (bars) and set colors individually
for color, bar in zip(['red','blue','green'], ax.patches):
    bar.set_color(color)
plt.show()

Outputs:

enter image description here

dm2
  • 4,053
  • 3
  • 17
  • 28