简体   繁体   中英

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()

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") 

在此输入图像描述

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