2

Going by the this example, http://matplotlib.org/examples/pylab_examples/barchart_demo.html

I wanted to generated the dynamic bar chart.so far I have following script.

import sys
import matplotlib.pyplot as plt
import numpy as np

groups = int(sys.argv[1])

subgroup = int(sys.argv[2])

fig, ax = plt.subplots()

index = np.arange(groups)

print index

bar_width = 1.0 / (subgroup + 1)

print bar_width

mainlist = []


for x in range(0, groups):
    #print x
    templist = []
    for num in range(0, subgroup):
        templist.append(num+1)
    #print templist
    mainlist.append(templist)

print mainlist

for cnt in range(0,subgroup):
    plt.bar(index + (bar_width * cnt), mainlist[cnt], bar_width)

plt.savefig('odd_bar_chart.png')

This works fine when i pass same values for groups and subgroup,

> odd_bar_chart.py 3 3
> odd_bar_chart.py 2 2

but if i pass different values like this,

odd_bar_chart.py 3 2 odd_bar_chart.py 2 3

it gives following error AssertionError: incompatible sizes: argument 'height' must be length {first argument} or scalar

Now I dont know hw height comes in picture ? can anybody tell me whats wrong here ?

1
  • The list in mainlist[cnt] has the length of subgroup while index has the length of group. You cant plot like that if they have different lengths. Commented Sep 18, 2013 at 6:37

1 Answer 1

2

Take a look at the docs for plt.bar. Here the first two arguments are left and height referring the value of the left hand side of the bar and it's height.

Your error message is informing you that the second argument, height should be either the same length as the first or a scalar (single value).

The error: In your iteration at the end you plot the height mainlist[cnt] against the left locations index + (bar_width * cnt). Clearly you are trying to adjust the x location to spatially separate the bar plots using the bar_with*cnt so this is a scalar. The length then of the left is given by index, which is generated from index = np.arange(groups) and so will have length group. But the length of the heights is given by subgroup, this is done when templist (which has length subgroup) is appended to mainlist.

So your error comes in the way you are generating your data. It is usually better to either stick something in by hand (as they have done in the example you referenced), or use something form numpy.random to generate a set of random numbers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.