How would you make a simple bar graph from a list of data?

data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0]

Recommended Answers

All 10 Replies

Hi!

for i in data:
    print "#" * i

:)

Regards, mawe

Gruess Gott mawe!
Your solution is very simple and very sweet! The elegance of Python keeps amazing an old programmer like me.

Here I was thinking Tkinter and rectangles. Well, I am almost done with that much more fancy/complicated solution. I guess I will just stick it into the code snippets.

Member Avatar for Mouche

Wow. Genius, Mawe.

Thanks mawe, that will come in handy! Also thanks to vegaseat for the beauty of a bar graph made with Tkinter, that is my first intro to Tkinter. Looks like GUI programming is much simpler than with other languages.

I tried to transpose mawe's horizontal simple bargraph into a vertical simple bargraph, but with no success. Has anybody tried this before?

Make something like this:

##########
#####
##
#

Look like this:

#
#
#
#
#
# #
# #
# #
# # #
# # # #

Hi!

def ascii_barchart( lst ):
    for row in range( max(lst), 0, -1 ):
        for elem in lst:
            if elem >= row: 
                print "# ",
            else: 
                print "  ",
        print

l = [20, 10, 15, 5]
ascii_barchart( l )

Not as simple as the first one, but ... still quite simple ;)

Regards, mawe

commented: nice code +5

Mawe sure knows how to keep it simple and elegant! Here is my contribution to mawe's original horizontal bar graph, I added one line of actual data value markers to the end, still simple:

data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0]

# pad each bar with spaces to total length of max(data), here 20
bar_list = []
for x in data:
    str1 = "#" * x
    # space pad to the right
    str2 = str1.ljust(max(data))
    bar_list.append(str2)

# test it, also show data value marker at end
for index, item in enumerate(bar_list):
    print item, '  -', data[index]

How do you mkae a bar graph were you enter 6 grades?

if zero = true 
then else if zero = false

Hi!

for i in data:
    print "#" * i

:)

Regards, mawe

:-O

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.