Pandas / matplotlib plot chart with colors defined by column

I am trying to create a histogram in python and colored columns by column of a dataframe, it is very simple in R ggplot2, so I really do who does not understand why it is so difficult in matplotlib / pandas, I would like to understand how to do it and hopefully logic as I suppose it can't be hard in the end

Here's an example of what I want. I did it in ggplot - all I want is to define the color using attributes in the dataframe, the attribute could be a color string ie 'k', 'r' .. or a data characteristic like man / woman, etc. etc. enter image description here

this is the example code i tried to use to create columns

import matplotlib.pyplot as plt
import pandas as pd
data = pd.DataFrame({'name' : ['a','b','c'],'value' : [1,2,3], 
                     'c' : ['b','r','b']})
data.plot('name','value',kind='bar')

      

but I want the color to be defined in column 'c'

but when i add color = 'c' then it doesn't work

data.plot('name','value',color='c',kind='bar',color='c')

      

I also tried using plot.scatter and it didn't work.

---- Update

I've done some more work and it works more or less, I still have to figure out how to align the labels correctly, I still love why I have to have a numeric x-axis when it is really categorical (again ggplot2 handles this on its own ) - but at least it can be done in code

fig, ax = plt.subplots()
ax.bar(range(len(data)),data['value'],width=.5,color=data['c'])
ax.set_xticks(range(len(data)))
ax.set_xticklabels( (data['name'] ))

      

Thanks as always

+3


source to share


1 answer


Try the following:

data.plot('name','value',color=['r', 'g', 'b'],kind='bar')

      

You can give any combination of colors as a list as a color argument. If the number of bars is greater than the number of colors, the colors will simply be processed.

enter image description here

I can also highly recommend the excellent brewer2mpl library. It provides an aesthetically pleasing color choice. The code looks like this:



import brewer2mpl
bmap = brewer2mpl.get_map('Set2','qualitative',3,reverse=True)
colors = bmap.mpl_colors
data.plot('name','value',color=colors,kind='bar')

      

as a result:

enter image description here

You can get brewer2mpl from here: https://pypi.python.org/pypi/brewer2mpl/1.4

+1


source







All Articles