How to plot a histogram by different groups in matplotlib

I have a table like:

value    type
10       0
12       1
13       1
14       2

Generate a dummy data:

import numpy as np

value = np.random.randint(1, 20, 10)
type = np.random.choice([0, 1, 2], 10)

I want to accomplish a task in Python 3 with matplotlib (v1.4):

  • plot a histogram of value
  • group by type , ie use different colors to differentiate types
  • the position of the "bars" should be "dodge", ie side by side
  • since the range of value is small, I would use identity for bins, ie the width of a bin is 1
  • The questions are:

  • how to assign colors to bars based on the values of type and draw colors from colormap (eg Accent or other cmap in matplotlib)? I don't want to use named color (ie 'b', 'k', 'r' )
  • the bars in my histogram overlap each other, how to "dodge" the bars?

  • Note (lest the post will be down voted and deemed to be "naive")

  • I have tried on Seaborn, matplotlib and pandas.plot for two hours and failed to get the desired histogram.
  • I read the examples and Users' Guide of matplotlib. Surprisingly, I found no tutorial about how to assign colors from colormap.
  • I have searched on Google but failed to find a succinct example.
  • I guess one could accomplish the task with matplotlib.pyplot , without import a bunch of modules such as matplotlib.cm , matplotlib.colors .

  • For your first question, we can create a dummy column equal to 1, and then generate counts by summing this column, grouped by value and type.

    For your second question you can pass the colormap directly into plot using the colormap parameter:

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    import seaborn
    seaborn.set() #make the plots look pretty
    
    df = pd.DataFrame({'value': value, 'type': type})
    df['dummy'] = 1
    ag = df.groupby(['value','type']).sum().unstack()
    ag.columns = ag.columns.droplevel()
    
    ag.plot(kind = 'bar', colormap = cm.Accent, width = 1)
    plt.show()
    

    在这里输入图像描述

    链接地址: http://www.djcxy.com/p/67602.html

    上一篇: 如何在条形图中设置y轴上的值

    下一篇: 如何绘制matplotlib中不同组的直方图