Question:
I have a pandas dataframe df with 6 rows representing different variables.
I want to plot the two first columns in a bar graph and I would like to use the third column score to colorize the bars based on an existing colormap, for example the matplotlib viridis one.
This dataframe looks like this:
ID count score
0 4 1 3
1 5 4 4
2 5 8 5
3 3 7 2
4 1 5 5
5 1 3 4
What my code looks like for the moment:
df.plot('ID', 'count', kind='bar', figsize=(15,5), ax=plt.subplot(122), colors=cm.viridis.colors)
plt.show()
But the color of all bar is a unique purple.
I want, let say, to sample the viridis colormap proportionally to values in my score column.
Is there a simple way to achieve that?
Edit [2019-10-31]:
Using seaborn as proposed in the first answer gives me an error:
my_palette = sns.color_palette(plt.get_cmap('viridis'), 5)
sns.barplot(x="New ID", y="count", hue="Note", data=df, palette=my_palette)
The error returned:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-1943cafa0d79> in <module>
----> 1 my_palette = sns.color_palette(plt.get_cmap('viridis'), 5)
/usr/local/lib/python3.6/dist-packages/seaborn/palettes.py in color_palette(palette, n_colors, desat)
238
239 # Always return as many colors as we asked for
--> 240 pal_cycle = cycle(palette)
241 palette = [next(pal_cycle) for _ in range(n_colors)]
242
TypeError: 'ListedColormap' object is not iterable
Edit [2019-11-05]:
Using the proposed code lead the resulting graph to have misaligned bars with the x-ticks (which I expected to be centered under the bar on the x-axis), especially when there is only one bar per category as the next figure shows:
In addition, I would like to be able to take into consideration 'NaN' values in the df['count'] column.
Currently, if there is one 'NaN' value, it raises a:
TypeError: unsupported operand type(s) for /: 'str' and 'int'
So, I have to set this value equal to 0 even if it is NOT truly a zero.



countattribute, there is actually no bar. So, the color doesn't matter.