简体   繁体   中英

Matplotlib Histogram not equal data sets

I would like to create a histogram that will use the following. I know this is because lengths of my menMeans and womenMeans are not equal. If I was not hard coding the list, and possible wanted to add some more list later to provide more bars how would I do this? What is the best way to scale the graph with knowing that the bars will not always have like sets of values.

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

## the data
N = 5
menMeans = [18, 35, 30, 35, 27] ### len=5
womenMeans = [25, 32, 34, 20, 25,42] ### len =6


## necessary variables
ind = np.arange(N)                # the x locations for the groups
width = 0.35                      # the width of the bars

## the bars
rects1 = ax.bar(ind, menMeans, width,
                color='black')

rects2 = ax.bar(ind+width, womenMeans, width,
                    color='red')

# axes and labels
ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0,45)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
xTickMarks = ['Group'+str(i) for i in range(1,7)]
ax.set_xticks(ind+width)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=45, fontsize=10)

## add a legend
ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

plt.show()

The error I get is:

Traceback (most recent call last):
  File "C:\Python27\test_3.py", line 22, in <module>
    color='red')
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 4999, in bar
    nbars)
AssertionError: incompatible sizes: argument 'height' must be length 5 or scalar

I think the easiest way to address this would be to add one or more zero means to the men's list until it's the same length as the other one. The extra zero means don't change the appearance of the graph - it just looks like the bar is absent:

在此处输入图片说明

Here's a simple general function to do that:

def equalizeLists(*lists):
    maxLen = max([len(list) for list in lists])
    for list in lists:
        list = list.extend([0]*(maxLen - len(list)))
    return maxLen

This will equalize the lengths of two or more lists automatically by adding zeros to the ends of the shorter ones. You could insert it into your code like so:

## the data
menMeans = [18, 35, 30, 35, 27] 
womenMeans = [25, 32, 34, 20, 25,42]
N = equalizeLists(menMeans, womenMeans)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM