├── README.md └── main.py /README.md: -------------------------------------------------------------------------------- 1 | # pyplot 2 | An example of using matplotlib.pyplot 3 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # coding:utf8 2 | from datetime import datetime 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | from dateutil import rrule 6 | import load_data 7 | import random 8 | def compare_key2num(elem): 9 | return int(elem[0]) 10 | 11 | def compare_value(elem): 12 | return int(elem[1]) 13 | 14 | def generate_graph(graph_type, keys, values, title, xlabel=None, ylabel=None,labels=None,xlim=None, ylim=None, marker=None, tag=False, accumulate=False): 15 | bar_width = 0.45 16 | n = len(values) 17 | for i in range(n): 18 | if graph_type == 'bar': 19 | accumulate_height = values[0] 20 | if i == 0: 21 | plt.bar(range(len(keys[i])), values[i], label=labels[i], align='center', alpha=0.8, width=bar_width) 22 | if tag: 23 | for x, y in enumerate(values[i]): 24 | plt.text(x, y + 5, '%s' % y, ha='center') 25 | else: 26 | if accumulate == False: 27 | plt.bar(np.arange(len(keys[i])) + i*bar_width, values[i], label=labels[i], align='center', alpha=0.8, width=bar_width) 28 | else: 29 | plt.bar(np.arange(len(keys[i])), values[i], label=labels[i], align='center', alpha=0.8, width=bar_width, bottom=accumulate_height) 30 | for ah in range(len(accumulate_height)): 31 | accumulate_height[ah] += values[i][ah] 32 | if tag: 33 | for x, y in enumerate(values[i]): 34 | plt.text(x+i*bar_width, y + 5, '%s' % y, ha='center') 35 | 36 | elif graph_type == 'plot': 37 | linestyles = ['-.','-','--',':'] 38 | plt.plot(keys[i], values[i], marker=marker, label=labels[i],linestyle=linestyles[random.randint(-1,3)]) 39 | if tag: 40 | for x, y in enumerate(values[i]): 41 | plt.text(x, y + 5, '%s' % y, ha='center') 42 | 43 | elif graph_type == 'pie': 44 | patches, l_text, p_text = plt.pie(values, labels=keys, autopct='%3.1f%%', shadow=False, startangle=90, pctdistance=0.6) 45 | for t in l_text: 46 | t.set_size = (10) 47 | for t in p_text: 48 | t.set_size = (10) 49 | plt.axis('equal') 50 | break 51 | 52 | plt.title(title) 53 | 54 | if graph_type == 'bar': 55 | # xticks 56 | if accumulate == False: 57 | plt.xticks(np.arange(len(keys[0])) + 0.5 * (n-1) * bar_width, keys[0]) 58 | else: 59 | plt.xticks(np.arange(len(keys[0])), keys[0]) 60 | 61 | if graph_type == 'bar' or graph_type == 'plot': 62 | if xlabel != None: 63 | plt.xlabel(xlabel) 64 | if ylabel != None: 65 | plt.ylabel(ylabel) 66 | if xlim != None: 67 | plt.xlim(xlim) 68 | if ylim != None: 69 | plt.ylim(ylim) 70 | 71 | plt.legend() 72 | plt.show() 73 | --------------------------------------------------------------------------------