Pandas + Matplotlib, Make one color in barplot stand out

matplotlib, pandas, python

Solution

I think mgilson's approach is the best were you add the data from Pandas in a Matplotlib command. You could however also capture the `axes` object which Pandas returns and then iterate over the artists to modify them.

This gets really tricky, because the bars don't have a label (its "_no_legend_") as an identifier, the only way to target a specific bar is to look-up its position in the index of the original `DataFrame`. Any change, like sorting, in the order between plotting and looking it up will give a wrong result!

import pandas as pd

df = pd.DataFrame({'contribution': [0.188137,0.160208,0.160208,0.151654,0.149489,0.135975,0.063206]}
                  ,index=['A','B','C','D','E','F','G'])

colors = ['b', 'green', 'y', 'pink','orange','cyan','darkgrey']

ax = df.plot(kind='barh', color=colors, legend=False)

for bar in ax.patches:
    bar.set_facecolor('#888888')

highlight = 'D'
pos = df.index.get_loc(highlight)

ax.patches[pos].set_facecolor('#aa3333')
ax.legend()

So this example gives only a little bit of insight in how Pandas and Matplotlib work together. I don't recommend actually using it and suggest just to go with mgnilson's approach.

Problem

I have a barplot with different colors. I would like to make one bar stand out with brighter colors and the others faded. My guess is to use the keyword alpha on the bars to fade them, but I can not figure out how to make one keep the original color (= not faded with alpha keyword). I need help on this Here is my code: ``` from matplotlib import pyplot as plt from itertools import cycle, islice import pandas as pd, numpy as np ds2=ds[['Factors', 'contribution']] ds3=ds2.set_index('Factors') it = cycle(['b', 'green', 'y', 'pink','orange','cyan','darkgrey']) my_colors=[next(it) for i in xrange(len(ds))] figure(1, figsize=(10,8)) # Specify this list of colors as the `color` option to `plot`. ds3.plot(kind='barh', stacked=True, color=my_colors, alpha=0.95) plt.title('xxxxxxxxxxxxxx', fontsize = 10) ``` Here is my simple dataframe ds3 ``` contribution Factors A 0.188137 B 0.160208 C 0.160208 D 0.151654 E 0.149489 F 0.135975 G 0.063206 ```

Original source