用python的matplotlib库绘制柱状图和饼图

毕业设计有一个需求,有一系列选择题,每个题目有四个选项,现在需要统计每个选项的人数,也就是画出柱状图和饼图。在网上找到了matplotlib这个库,折腾了几个小时,总算把需要的功能实现了。这个库一开始看起来是没有多少头绪的,很多函数也不知道什么意思,我感觉最好的学习方式就是按照需求,找到对应的gallery示例demo,然后按照需求来改,慢慢就知道怎么做了。只是看教程的话会感觉没有头绪,但是还是推荐先看几篇入门教程。

###用matplotlib绘制柱状图
主要参考了这两个demo:
http://matplotlib.org/examples/pylab_examples/barchart_demo.html

http://matplotlib.org/examples/api/barchart_demo.html

现在照葫芦画瓢来个自己的:

#coding=utf-8
"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体,解决中文显示问题

n_groups = 6

means_men = (20, 35, 30, 35, 27, 18)
#std_men = (2, 3, 4, 1, 2)

means_women = (25, 32, 34, 20, 25, 18)
#std_women = (3, 5, 2, 3, 3)

fig, ax = plt.subplots()

index = np.arange(n_groups)
#bar_width = 0.35
bar_width = 0.2

opacity = 0.4
error_config = {'ecolor': '0.3'}

rects1 = plt.bar(index, means_men, bar_width,
                 alpha=opacity,
                 color='b',
                 #yerr=std_men,
                 error_kw=error_config,
                 label='Men')

rects2 = plt.bar(index + bar_width, means_women, bar_width,
                 alpha=opacity,
                 color='r',
                 #yerr=std_women,
                 error_kw=error_config,
                 label='Women')

rects3 = plt.bar(index+bar_width*2, means_men, bar_width,
                 alpha=opacity,
                 color='b',
                 #yerr=std_men,
                 error_kw=error_config,
                 label='Men')

rects4 = plt.bar(index+bar_width*3, means_men, bar_width,
                 alpha=opacity,
                 color='g',
                 #yerr=std_men,
                 error_kw=error_config,
                 label='Men')

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2.0, 1.05*height, 
                '%d'%int(height), ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
autolabel(rects4)


plt.xlabel(u'题号')
plt.ylabel(u'人数')
plt.title(u'答题结果统计')
plt.xticks(index + bar_width, ('1', '2', '3', '4', '5', '6'))
#plt.legend()
ax.set_ybound(0, 40)

plt.tight_layout()
plt.show()
#plt.savefig(u't.png')

###用matplotlib绘制饼图
这个就比较简单啦,直接看demo就可以了。

"""
Demo of a basic pie chart plus a few additional features.

In addition to the basic pie chart, this demo shows a few optional features:

    * slice labels
    * auto-labeling the percentage
    * offsetting a slice with "explode"
    * drop-shadow
    * custom start angle

Note about the custom start angle:

The default ``startangle`` is 0, which would start the "Frogs" slice on the
positive x-axis. This example sets ``startangle = 90`` such that everything is
rotated counter-clockwise by 90 degrees, and the frog slice starts on the
positive y-axis.
"""
import matplotlib.pyplot as plt


# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')

plt.show()

饼图显示效果

###Ref
matplotlib
python使用matplotlib绘图 – barChart
绘图: matplotlib核心剖析
python使用matplotlib绘图详解