python - Matplotlib Histogram not equal data sets -
i create histogram use following. know because lengths of menmeans , womenmeans not equal. if not hard coding list, , possible wanted add more list later provide more bars how this? best way scale graph knowing bars not have sets of values.
import numpy np import matplotlib.pyplot plt fig = plt.figure() ax = fig.add_subplot(111) ## 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) # x locations groups width = 0.35 # width of bars ## bars rects1 = ax.bar(ind, menmeans, width, color='black') rects2 = ax.bar(ind+width, womenmeans, width, color='red') # axes , labels ax.set_xlim(-width,len(ind)+width) ax.set_ylim(0,45) ax.set_ylabel('scores') ax.set_title('scores group , gender') xtickmarks = ['group'+str(i) in range(1,7)] ax.set_xticks(ind+width) xticknames = ax.set_xticklabels(xtickmarks) plt.setp(xticknames, rotation=45, fontsize=10) ## add legend ax.legend( (rects1[0], rects2[0]), ('men', 'women') ) plt.show()
the error 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 length 5 or scalar
i think easiest way address add 1 or more 0 means men's list until it's same length other one. 0 means don't change appearance of graph - looks bar absent:
here's simple general function that:
def equalizelists(*lists): maxlen = max([len(list) list in lists]) list in lists: list = list.extend([0]*(maxlen - len(list))) return maxlen
this equalize lengths of 2 or more lists automatically adding zeros ends of shorter ones. insert code so:
## data menmeans = [18, 35, 30, 35, 27] womenmeans = [25, 32, 34, 20, 25,42] n = equalizelists(menmeans, womenmeans)
Comments
Post a Comment