博客
关于我
matplot绘制图形入门
阅读量:800 次
发布时间:2023-02-07

本文共 5250 字,大约阅读时间需要 17 分钟。

一、折线图

"""File: 折线图.pyAuthor: chde_wangDate: 2021-05-23 22:26:04Description:"""# 绘制折线图import numpy as npimport matplotlib.pyplot as pltx = np.linspace(0, 2 * np.pi, 100)y1, y2 = np.sin(x), np.cos(x)plt.plot(x, y1)plt.plot(x, y2)plt.title('line chart')plt.xlabel('x')plt.ylabel('y')plt.show()# 指定图例:label# 指定颜色:c# 指定线型:关键字参数linestyle(或ls)用来设置线的样式。可取值为:# -, solid# --, dashed# -., dashdot# :, dotted# 关键字参数linewidth(或lw)可以改变线的粗细# marker的样式:"o" "x" "v"x = np.linspace(0, 2 * np.pi, 100)y1, y2 = np.sin(x), np.cos(x)plt.plot(x, y1, label='y = sin(x)', c='r', linestyle='dashed', lw=5)plt.plot(x, y2, label='y = cos(x)', c='y', marker=">")plt.legend()plt.show()

二、柱状图

"""File: 柱状图.pyAuthor: chde_wangDate: 2021-05-23 22:08:14Description:"""import matplotlib as plt# -*- coding: utf-8 -*-import matplotlib.pyplot as pltnum_list = [1.5, 0.6, 7.8, 6]print(range(len(num_list)))plt.bar(range(len(num_list)), num_list)plt.show()num_list = [1.5, 0.6, 7.8, 6]print(range(len(num_list)))plt.bar(range(len(num_list)), num_list,fc='r')  #设置颜色fc,彩色:rgbplt.show()name_list = ['Monday', 'Tuesday', 'Friday', 'Sunday']num_list = [1.5, 0.6, 7.8, 6]plt.bar(range(len(num_list)), num_list, color='rgb', tick_label=name_list)plt.show()name_list = ['Monday', 'Tuesday', 'Friday', 'Sunday']num_list = [1.5, 0.6, 7.8, 6]num_list1 = [1, 2, 3, 1]x = list(range(len(num_list)))total_width, n = 0.8, 2width = total_width / nplt.bar(x, num_list, width=width, label='boy', fc='y')for i in range(len(x)):    x[i] = x[i] + widthplt.bar(x, num_list1, width=width, label='girl', tick_label=name_list, fc='r')plt.legend()plt.show()

三饼图

"""File: 饼图.pyAuthor: chde_wangDate: 2021-05-23 22:40:32Description:"""#!/usr/bin/env python#!-*-coding:utf-8 -*-#!@Author : Biyoulin#!@Time   : 2018/9/4 10:45import matplotlib.pyplot as pltplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签# x       :(每一块)的比例,如果sum(x) > 1会使用sum(x)归一化;# labels  :(每一块)饼图外侧显示的说明文字;# explode :(每一块)离开中心距离;# startangle :起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起;# shadow  :在饼图下面画一个阴影。默认值:False,即不画阴影;# labeldistance :label标记的绘制位置,相对于半径的比例,默认值为1.1, 如<1则绘制在饼图内侧;# autopct :控制饼图内百分比设置,可以使用format字符串或者format function#         '%1.1f'指小数点前后位数(没有用空格补齐);# pctdistance :类似于labeldistance,指定autopct的位置刻度,默认值为0.6;# radius  :控制饼图半径,默认值为1;counterclock :指定指针方向;布尔值,可选参数,默认为:True,即逆时针。将值改为False即可改为顺时针。wedgeprops :字典类型,可选参数,默认值:None。参数字典传递给wedge对象用来画一个饼图。例如:wedgeprops={'linewidth':3}设置wedge线宽为3。# textprops :设置标签(labels)和比例文字的格式;字典类型,可选参数,默认值为:None。传递给text对象的字典参数。# center :浮点类型的列表,可选参数,默认值:(0,0)。图标中心位置。# frame :布尔类型,可选参数,默认值:False。如果是true,绘制带有表的轴框架。# rotatelabels :布尔类型,可选参数,默认为:False。如果为True,旋转每个label到指定的角度。# labels = ['娱乐','育儿','饮食','房贷','交通','其它']sizes = [2,5,12,70,2,9]explode = (0,0,0,0.1,0,0)plt.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',shadow=False,startangle=150)plt.title("饼图示例-8月份家庭支出")plt.show()

四词图

import jiebaimport numpy as npfrom PIL import Imagefrom wordcloud import WordCloudimport matplotlib.pyplot as pltpic_mask=np.array(Image.open("ty.jpg"))#获取词云形状的图片text=open(r'kebiao.txt',encoding='utf8')#获取分词数据mylist=list(text)word_list=[" ".join(jieba.cut(sentence)) for sentence in mylist]new_text=' '.join(word_list)wordcloud=WordCloud(font_path='simhei.ttf',background_color="white", #显示的字体和背景颜色                    max_words=500,#出现次数最多的前500个分词                    max_font_size=150,#显示的最大字号                    random_state=40,#分词颜色的随机配色方案数量                    mask=pic_mask) #词云形状w=wordcloud.generate(new_text)#传入分词列表plt.imshow(w)#绘制词云图plt.axis("off")#关闭坐标plt.show()#显示词云图import matplotlib.pyplot as pltplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签labels = 'A','B','C','D'sizes = [10,10,10,70]plt.pie(sizes,labels=labels)plt.title("饼图详解示例")plt.text(1,-1.2,'By:Biyoulin')plt.show()

# -*- coding: utf-8 -*-import jiebaimport numpy as npfrom PIL import Imagefrom wordcloud import WordCloudimport matplotlib.pyplot as pltimport bs4import requests#爬取商品标题数据url = 'https://re.taobao.com/search?keyword=%E8%BF%9B%E5%8F%A3%E9%9B%B6%E9%A3%9F&catid=50010550&refpid=619362_1007&_input_charset=utf8&clk1=b93e1915c335dd925dfcbf24ae696b12&spm=a21bo.2017.201874-p4p.7.5af911d9f5vIK4'      # 网址payload = {'SearchText': 'taob', 'page': '1', 'ie': 'utf8', 'g': 'y'}  # 字典传递url参数title = []# 爬取商品标题for i in range(0, 10):        # 循环10次,就是10个页面的商品数据        payload['page'] = i    # 此处为页码,根据网页参数具体设置        resp = requests.get(url, params=payload)        soup = bs4.BeautifulSoup(resp.text, "html.parser")        # print(resp.url)          # 打印访问的网址        resp.encoding = 'utf-8'  # 设置编码        # 标题        all_title = soup.find_all('span', class_="title")        for j in all_title:            soup_title = bs4.BeautifulSoup(str(j), "html.parser",)            title.append(soup_title.span.string)print(title)#商品标题词云图pic_mask=np.array(Image.open("ty.jpg"))#获取词云形状的图片print(len(title))for i in title:       words = jieba.lcut(i)       new_text=' '.join(words)wordcloud=WordCloud(font_path='simhei.ttf',background_color="white", #显示的字体和背景颜色                    max_words=100,#出现次数最多的前100个分词                    max_font_size=150,#显示的最大字号                    random_state=10,#分词颜色的随机配色方案数量                    mask=pic_mask) #词云形状w=wordcloud.generate(new_text)#传入分词列表plt.imshow(w)#绘制词云图plt.axis("off")#关闭坐标plt.show()#显示词云图

转载地址:http://bcyfk.baihongyu.com/

你可能感兴趣的文章
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 参数--lock-tables浅析
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump 导出数据库中每张表的前n条
查看>>
mysqldump: Got error: 1044: Access denied for user ‘xx’@’xx’ to database ‘xx’ when using LOCK TABLES
查看>>
Mysqldump参数大全(参数来源于mysql5.5.19源码)
查看>>
mysqldump备份时忽略某些表
查看>>
mysqldump实现数据备份及灾难恢复
查看>>
mysqldump数据库备份无法进行操作只能查询 --single-transaction
查看>>
mysqldump的一些用法
查看>>
mysqli
查看>>
MySQLIntegrityConstraintViolationException异常处理
查看>>
mysqlreport分析工具详解
查看>>
MySQLSyntaxErrorException: Unknown error 1146和SQLSyntaxErrorException: Unknown error 1146
查看>>
Mysql_Postgresql中_geometry数据操作_st_astext_GeomFromEWKT函数_在java中转换geometry的16进制数据---PostgreSQL工作笔记007
查看>>
mysql_real_connect 参数注意
查看>>
mysql_secure_installation初始化数据库报Access denied
查看>>
MySQL_西安11月销售昨日未上架的产品_20161212
查看>>
Mysql——深入浅出InnoDB底层原理
查看>>