学习Python第三天

图形绘制

1.正弦余弦图

from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
# 使用100个点,绘制[0, 2∏]正弦曲线图
# .linspace 左闭右闭区间的等差数列
x = np.linspace(0, 2*np.pi, num=100)
print(x)
y = np.sin(x)
# 正弦和余弦在同一坐标系下
cosy = np.cos(x)
plt.plot(x, y,color='g',linestyle='--',label='sin(x)')
plt.plot(x,cosy, color='r',label='cos(x)')
plt.xlabel('时间(s)')
plt.ylabel('电压(v)')
plt.title('欢迎来到Python的世界')
image.png

2.柱状图

# 导入
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
# 柱状图
import string
from random import randint
# print(string.ascii_uppercase[0,6])
# ['A','B','C',...]
x = ['口红{}'.format(x) for x in string.ascii_uppercase[:5]]
y = [randint(200, 500) for _ in range(5)]
print(x)
print(y)
plt.xlabel('口红品牌')
plt.ylabel('价格(元)')
plt.bar(x,y)
plt.show()
image.png

3.饼状图

from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
# # 饼图
from random import randint
import string
counts = [randint(3500,9000) for _ in range(6)]
labels = ['员工{}'.format(x) for x in string.ascii_lowercase[:6]]
# 距离圆心点距离
explode = [0.1,0,0,0,0,0]
colors = ['red','purple','blue','yellow','gray','green']
plt.pie(counts,explode = explode,shadow=True,labels=labels,autopct='%1.1f%%',colors=colors)
plt.legend(loc=2)
plt.axis('equal')
plt.show()
image.png

4.散点图

from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import numpy as np
x = np.random.normal(0, 1, 1000000)
y = np.random.normal(0, 1, 1000000)
# alpha透明度
plt.scatter(x, y, alpha=0.1)
plt.show()
image.png

小作业

1.三国top10人物分析饼状图

import jieba
from wordcloud import WordCloud
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import string
# 1.读取小说
with open('./novel/threekingdom.txt', 'r', encoding='utf-8') as f:
    words = f.read()
    counts = {}
    excludes = {"将军", "却说", "丞相", "二人", "不可", "荆州", "不能", "如此", "商议",
                "如何", "主公", "军士", "军马", "左右", "次日", "引兵", "大喜", "天下",
                "东吴", "于是", "今日", "不敢", "魏兵", "陛下", "都督", "人马", "不知",
                "孔明曰", "玄德曰", "刘备", "云长"}
    # 2.分词
    words_list = jieba.lcut(words)
    # print(words_list)
    for word in words_list:
        if len(word) <= 1:
            continue
        else:
            # 更新字典中的值
            # counts[word] = counts[word] + 1
            # 字典.get(k) 如果字典中没有这个键 返回none
            counts[word] = counts.get(word, 0) + 1
    print(len(counts))
    # 3.词语过滤,删除无关词、重复词
    counts['孔明'] = counts['孔明'] + counts['孔明曰']
    counts['玄德'] = counts['玄德'] + counts['玄德曰']
    counts['玄德'] = counts['玄德'] + counts['玄德曰'] + counts['刘备']
    counts['关公'] = counts['关公'] + counts['云长']
    for word in excludes:
        del counts[word]
    # 4.排序
    items = list(counts.items())
    print(items)
    items.sort(key=lambda x: x[1], reverse=True)
    li = []  # ['孔明',...'曹操',...]
    count1 = []
    count2 = []
    for i in range(10):
        # 序列解包
        role, count = items[i]
        print(role, count)
        count1.append(role)
        count2.append(count)
        # _是告诉循环里面不需要使用临时变量
        for _ in range(count):
            li.append(role)
    # 5.得出结论
    text = ' '.join(li)
    WordCloud(
        font_path='msyh.ttc',
        background_color='white',
        width=800,
        height=600,
        # 相邻两个重复词之间的匹配
        collocations=False
    ).generate(text).to_file('./TOP10.png')
    # 6.绘制三国TOP10饼图
    plt.pie(count2, shadow=True, labels=count1, autopct='%1.lf%%')
    plt.legend(loc=2)
    plt.axis('equal')
    plt.show()
image.png

2.红楼梦top10人物分析

import jieba
with open("./novel/all.txt",'r',encoding='utf-8') as f:
    words = f.read()
    count = {}
    words_list = jieba.lcut(words) #精确分词
    for i in words_list:
        if len(i) <= 1:
            continue
        else:
            count[i] = count.get(i, 0)+1
    print(count)
    excludes = {'什么', '一个', '我们', '你们', '如今', '说道', '老太太', '知道', '姑娘', '起来',
                '这里', '出来', '众人', '那里', '奶奶' ,'自己', '太太', '一面', '只见', '两个',
                '没有', '怎么', '不是', '不知', '这个', '听见', '这样', '进来', '咱们', '就是',
                '东西', '告诉', '袭人', '回来', '就是', '只是', '大家', '老爷', '只得', '丫头',
                '这些', '他们', '不敢', '出去', '所以', '不过', '不好', '姐姐', '探春', '一时', '的话', '鸳鸯','凤姐'
                ,'过来','不能','心里','她们','如此','今日','二人','答应','几个','这么','还有','只管','说话'}
    count['凤姐儿'] = count['凤姐儿'] = count['凤姐']
    for i in excludes:
        del count[i] # 删除不是人名的高频词汇

items = list(count.items()) #将字典转换为列表
items.sort(key=lambda x: x[1], reverse=True) #使用匿名函数从大到小排序
# print(items)
li = []
lii = [] # 装人物
lli = [] # 装人物出现的次数
for i in range(10):
    role, count = items[i] #序列解包
    lli.append(count)
    lii.append(role)
    for _ in range(count):
        li.append(role) # 在li里循环写入 count个 role(人名)
    text = ' '.join(li) #将li转换为字符串
from wordcloud import WordCloud
import imageio
mask = imageio.imread('./image/china.jpg')
WordCloud(
font_path='msyh.ttc',
    background_color='black',
    width=800,
    height=600,
    collocations=False, #相邻两个重复词之间的匹配
    mask=mask
).generate(text).to_file('红楼梦.png')
image.png

你可能感兴趣的:(学习Python第三天)