Search code examples
pythonlistpython-3.5sublistplt

Python: Plotting sublists on matplotlib.pyplot


I wanted to plot list, with sublists, each containing name and score. Sublist item one = name as X-label, and item two = score as Y label.

datacount = (("mike", 9), ("john", 8), ("smith", 7), ("niki", 7), ("garlick", 7),
             ("don", 7), ("ross", 7), ("darli", 6), ("nick", 6), ("perl", 6), 
             ("cat", 5), ("dona", 4))

How can I plot this in plt?

I tried this like its dictionary, but it does not show all names and corresponding scores.

import matplotlib.pyplot as plt
datacount = D

plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), D.keys())

plt.show()

Solution

  • Assuming you have a list of tuples, you can use zip to unpack X and Y elements, and then do the bar plot; The tick_label can be used to label your x-axis:

    import matplotlib.pyplot as plt 
    %matplotlib inline
    
    plt.figure(figsize = (10, 7))
    
    X, Y = zip(*datacount)
    ax = plt.bar(range(len(X)), Y, 0.6, align='center', tick_label = X, color="sienna") 
    

    enter image description here