Pandas bar plot — specify bar color by column

后端 未结 2 795
予麋鹿
予麋鹿 2020-12-18 01:36

Is there a simply way to specify bar colors by column name using Pandas DataFrame.plot(kind=\'bar\') method?

I have a script that generates multiple Dat

相关标签:
2条回答
  • 2020-12-18 02:26

    Pandas version 1.1.0 makes this easier. You can pass a dictionary to specify different color for each column in the pandas.DataFrame.plot.bar() function:

    Here is an example:

    df1 = pd.DataFrame({'a': [1.2, .8, .9], 'b': [.2, .9, .7]})
    df2 = pd.DataFrame({'b': [0.2, .5, .4], 'c': [.5, .6, .7], 'd': [1.1, .6, .7]})
    color_dict = {'a':'green', 'b': 'red', 'c':'blue', 'd': 'cyan'}
    df1.plot.bar(color = color_dict)
    df2.plot.bar(color = color_dict)
    
    0 讨论(0)
  • 2020-12-18 02:28

    You can pass a list as the colors. This will require a little bit of manual work to get it to line up, unlike if you could pass a dictionary, but may be a less cluttered way to accomplish your goal.

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pds
    
    data_files = ['a', 'b', 'c', 'd']
    
    df1 = pds.DataFrame(np.random.rand(4,3), columns=data_files[:-1])
    df2 = pds.DataFrame(np.random.rand(4,3), columns=data_files[1:])
    
    color_list = ['b', 'g', 'r', 'c']
    
    
    df1.plot(kind='bar', ax=plt.subplot(121), color=color_list)
    df2.plot(kind='bar', ax=plt.subplot(122), color=color_list[1:])
    
    plt.show()
    

    enter image description here

    EDIT Ajean came up with a simple way to return a list of the correct colors from a dictionary:

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pds
    
    data_files = ['a', 'b', 'c', 'd']
    color_list = ['b', 'g', 'r', 'c']
    d2c = dict(zip(data_files, color_list))
    
    df1 = pds.DataFrame(np.random.rand(4,3), columns=data_files[:-1])
    df2 = pds.DataFrame(np.random.rand(4,3), columns=data_files[1:])
    
    df1.plot(kind='bar', ax=plt.subplot(121), color=map(d2c.get,df1.columns))
    df2.plot(kind='bar', ax=plt.subplot(122), color=map(d2c.get,df2.columns))
    
    plt.show()
    
    0 讨论(0)
提交回复
热议问题