python_使用matplotlib画饼状图

代码与详细注释

from matplotlib import pyplot as plt 

#调节图形大小,宽,高
plt.figure(figsize=(6,9))
#定义饼状图的标签,标签是列表
labels = [u'第一部分',u'第二部分',u'第三部分']
#每个标签占多大,会自动去算百分比
sizes = [60,30,10]
colors = ['red','yellowgreen','lightskyblue']
#将某部分爆炸出来, 使用括号,将第一块分割出来,数值的大小是分割出来的与其他两块的间隙
explode = (0.05,0,0)

patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors,
                                labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,
                                startangle = 90,pctdistance = 0.6)

#labeldistance,文本的位置离远点有多远,1.1指1.1倍半径的位置
#autopct,圆里面的文本格式,%3.1f%%表示小数有三位,整数有一位的浮点数
#shadow,饼是否有阴影
#startangle,起始角度,0,表示从0开始逆时针转,为第一块。一般选择从90度开始比较好看
#pctdistance,百分比的text离圆心的距离
#patches, l_texts, p_texts,为了得到饼图的返回值,p_texts饼图内部文本的,l_texts饼图外label的文本

#改变文本的大小
#方法是把每一个text遍历。调用set_size方法设置它的属性
for t in l_text:
    t.set_size=(30)
for t in p_text:
    t.set_size=(20)
# 设置x,y轴刻度一致,这样饼图才能是圆的
plt.axis('equal')
plt.legend()
plt.show()

输出效果如下: 

itdadao

# !usr/bin/env python
# -*- coding:utf-8 -*-
# author:feier time:2018-01-20
import string
from matplotlib import pyplot as plt
from zhon.hanzi import punctuation
 
def process_line(line,dict):
    l = []
    for word in line:
        word = word.strip(punctuation + string.whitespace)
        if word != "":
            l.append(word)
    # print(l)
    for word in l:
        dict[word] = dict.get(word, 0) + 1
    return dict
def process_file(filename):
    dict = {}
    with open(filename, 'r', encoding="utf-8") as f:
        for line in f:
            # print(line)
            process_line(line, dict)
    return dict
 
def get_num(dict, num):
    lis = []
    for key,value in dict.items():
        lis.append((value, key))
    lis.sort(reverse=True)
    lis = lis[:num]
    print(lis)
    return lis
 
def plot_(list):
    # 饼图显示中文
    plt.rcParams['font.sans-serif'] = ["SimHei"]
    #  图形的大小,宽、高。
    plt.figure(figsize=(6, 9))
    colors = ["red","orange","yellow","green","blue"]
    explode = (0.05, 0, 0, 0 ,0 )
    #   定义饼图的标签
    labels = [word[-1] for word in list]
    # print(labels)
    #    每个标签的数值大小
    sizes = [word[0] for word in list]
    # print(size)
    patches, l_text, p_text = plt.pie(sizes,labels=labels,labeldistance=1.1,
                                      autopct='%3.1f%%',shadow=False,startangle=90,
                                      pctdistance=0.6,colors=colors,explode=explode)
    for word in p_text:
        word.set_size(10)
 
 
    #    设置x/y轴刻度一致
    plt.axis('equal')
    #   标题
    plt.title('文字出现次数统计饼图')
    plt.show()
 
 
 
def main():
    """主函数"""
    #     第一步,获取、处理文本,拿到文字和数量的键值对
    dict = process_file("摄政王的小狼妃.txt")
    # print(dict)
    #    第二步,截取数量最多的前num序列
    lis = get_num(dict,5)
    #  第三步, 绘图
    plot_(lis)
 
if __name__ == "__main__":
    main()
其实就是把txt中每个字用strip分割开用dict的value来存储,dict的key拿来存储该value出现的次数。然后再用迭代器把dict转到list中存储,再用list的排序功能(降序排序reverse=true)和切片功能(只要前num位:list[:num]),从而list最终只留下num个文字-频数对。最后就是用matplotlib中的pyplot来画图了,设置好一些参数(关键的labels(list中的value)和sizes(list中的key),autopct好像是显示权值百分比)。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值