matplotlib数据可视化三分钟入门,半小时入魔?

一, 首先当然是配置环境了

在Windows的DOM窗口中输入如下命令(在pycharm下面的Terminal中同)

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib

(注:小编没有记错的话,这个包有五十多M,如果不加国内镜像源,将会持续下载几小时之久。。。)

二,3分钟快速入门

1,导入模块

import matplotlib.pyplot as plt

import numpy as np
import pandas as pd

2, 几种常见函数图像(y=x, y=x^2 +3, y=sin(x))

① y=x图像

x = np.linspace(-10, 10, 10)

plt.plot(x, x, marker='o', color='r', linestyle='--', linewidth=1, label='y=x')
plt.legend()
plt.show()

matplotlib数据可视化三分钟入门,半小时入魔?
注:代码简写
plt.plot(x, x, marker='o', color='r', linestyle='--', linewidth=1, label='y=x')

plt.plot(x, x, marker='o', c='r', ls='--', lw=1, label='y=x')

plt.plot(x, x, 'o--r', lw=1, label='y=x')

注:关于marker,color, linestyle中的参数还有很多,帮助手册中的内容如下

**Markers**

=============   ===============================
character       description
=============   ===============================
'.'         point marker
','         pixel marker
'o'         circle marker
'v'         triangle_down marker
'^'         triangle_up marker
'<' triangle_left marker '>'         triangle_right marker
'1'         tri_down marker
'2'         tri_up marker
'3'         tri_left marker
'4'         tri_right marker
'8'         octagon marker
's'         square marker
'p'         pentagon marker
'P'         plus (filled) marker
'*'         star marker
'h'         hexagon1 marker
'H'         hexagon2 marker
'+'         plus marker
'x'         x marker
'X'         x (filled) marker
'D'         diamond marker
'd'         thin_diamond marker
'|'         vline marker
'_'         hline marker
=============   ===============================

**Line Styles**

=============    ===============================
character        description
=============    ===============================
'-'          solid line style
'--'         dashed line style
'-.'         dash-dot line style
':'          dotted line style
=============    ===============================
**Colors**

The supported color abbreviations are the single letter codes

=============    ===============================
character        color
=============    ===============================
'b'          blue
'g'          green
'r'          red
'c'          cyan
'm'          magenta
'y'          yellow
'k'          black
'w'          white
=============    ===============================
</'>

② y=x^2 +3图像


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(-10, 10, 100)
y = x**2 + 3

plt.plot(x, y, '--g', lw=1, label='y=x^2+3')

plt.title('折线图', c='r', size=15)
plt.legend()
plt.show()

matplotlib数据可视化三分钟入门,半小时入魔?
③ y=sin(x)图像

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(-10, 10, 100)
y = np.sin(x)

plt.plot(x, y, '--g', lw=1, label='y=sin(x)')
plt.title('折线图', c='r', size=15)
plt.legend()
plt.xlabel('这是x轴', c='b', size=13)
plt.ylabel('这是y轴', c='k', size=13)
plt.xlim(-2*np.pi, 2*np.pi)
plt.ylim(-1, 1)
plt.xticks(np.arange(-2*np.pi, 2*np.pi, np.pi/4), rotation=45)
plt.yticks(np.arange(-1, 1.1, 0.2))
plt.show()

matplotlib数据可视化三分钟入门,半小时入魔?

④ 将3个图合成一张图


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(-5, 5, 100)
y1 = x
y2 = x**2 + 3
y3 = np.sin(x)

plt.figure(figsize=(9, 6))
plt.plot(x, y1, ':b', lw=2, label='y=x')
plt.plot(x, y2, '-r', lw=1, label='y=x^2+3')
plt.plot(x, y3, '--g', lw=1.5, label='y=sin(x)')
plt.title('折线图', c='r', size=15)
plt.legend()
plt.xlabel('这是x轴', c='b', size=13)
plt.ylabel('这是y轴', c='k', size=13)
plt.show()

matplotlib数据可视化三分钟入门,半小时入魔?
⑤ 一张画布上画多张图

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(-5, 5, 100)
y1 = x
y2 = x**2 + 3
y3 = np.sin(x)
y4 = np.cos(x)

pf = plt.figure(figsize=(10, 7))
as1 = pf.add_subplot(2, 2, 1)
as2 = pf.add_subplot(2, 2, 2)
as3 = pf.add_subplot(2, 2, 3)
as4 = pf.add_subplot(2, 2, 4)
as1.plot(x, y1, ':b', lw=2, label='y=x')
as2.plot(x, y2, '-r', lw=1, label='y=x^2+3')
as3.plot(x, y3, '--g', lw=1.5, label='y=sin(x)')
as4.plot(x, y4, '-.k', lw=1.5, label='y=cos(x)')
as1.legend()
as2.legend()
as3.legend()
as4.legend()
plt.show()

matplotlib数据可视化三分钟入门,半小时入魔?

三,画柱状图


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = np.arange(1, 13)
y = np.random.randint(1, 50, 12)
lab = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

plt.figure(figsize=(9, 6.5))
plt.bar(x, y, color='b', tick_label=lab, label='柱形图')
plt.xticks(np.arange(1, 13))
plt.title('柱形图练习', color='b', size=13)
plt.legend()
plt.xlabel('箱子编号')
plt.ylabel('箱子大小')
plt.show()

matplotlib数据可视化三分钟入门,半小时入魔?

四,画饼图


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

kinds = ['哈士奇', '阿拉斯加', '萨摩耶', '黄毛狮王']
num = [0.3, 0.1, 0.2, 0.4]

plt.figure(figsize=(9, 6.5))

plt.pie(num, labels=kinds, autopct='%.2f%%', explode=[0, 0, 0.1, 0])
plt.show()

matplotlib数据可视化三分钟入门,半小时入魔?

五,小试牛刀

1,爬取数据

爬取某批发菜市场近一年菜价

import requests
from lxml import etree
import csv
from concurrent.futures import ThreadPoolExecutor
import time

f = open("vegetables.csv", mode="w", newline='', encoding="utf-8")
csv_write = csv.writer(f)

def down_one_page(url):
    res = requests.get(url=url, headers=headers).text

    html = etree.HTML(res)
    table = html.xpath('/html/body/div[2]/div[4]/div[1]/table')[0]

    trs = table.xpath('./tr[position()>1]')

    for tr in trs:
        txt = tr.xpath('./td/text()')

        txt = (item.replace("\\", "").replace("/", "") for item in txt)

        csv_write.writerow(list(txt))

    new_name = url.split("/")[-1].split(".")[0]
    print("第 \033[31;1m%s\033[0m 页下载完成!!!" % new_name)

if __name__ == '__main__':
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.54"
    }

    user_input = int(input("Total 15069 pages,please input a page number>>>:"))
    start_time = time.time()
    with ThreadPoolExecutor(32) as t:
        for i in range(1, user_input + 1):
            t.submit(down_one_page, "http://www.xinfadi.com.cn/marketanalysis/0/list/%s.shtml" % i)

    print("Download over,it takes \033[31;1m%s\033[0m seconds" % (time.time() - start_time))

matplotlib数据可视化三分钟入门,半小时入魔?
大约10万条数据!

2,数据的简单处理

先读取前几行看看数据

import pandas as pd

output_file = 'vage.csv'
vege_data = pd.read_csv('vegetables.csv', header=None)
print(vege_data.head(5))

     0     1     2     3    4  5           6
0  沙蜜托  20.0  22.5  25.0  樱桃类  斤  2021-05-15
1  羊上脑  42.0  42.5  43.0  羊肉类  斤  2021-05-15
2  羊骨头  11.0  11.5  12.0  羊肉类  斤  2021-05-15
3   羊腩  32.0  32.0  32.0  羊肉类  斤  2021-05-15
4  羊里脊  42.0  42.0  42.0  羊肉类  斤  2021-05-15

为了后面方便画图,对时间列进行排序

import pandas as pd

output_file = 'vage.csv'
vege_data = pd.read_csv('vegetables.csv', header=None, index_col=6).sort_index()
print(vege_data.head(5))

               0    1     2    3    4  5
6
2020-05-13    线茄  1.0  1.50  2.0  |粤云  斤
2020-05-13    苦菊  1.2  1.60  2.0    辽  斤
2020-05-13   油麦菜  1.2  1.50  1.8    辽  斤
2020-05-13    荸荠  1.8  1.90  2.0    皖  斤
2020-05-13  金丝南瓜  0.9  1.05  1.2  琼吊瓜  斤

筛选出’整牛’对应的所有行

import pandas as pd

output_file = 'vage.csv'
vege_data = pd.read_csv('vegetables.csv', header=None, index_col=6).sort_index()
new_data = vege_data[vege_data[0] == '整牛']
print(new_data)

             0      1      2      3    4  5
6
2020-05-15  整牛  30.00  30.50  31.00   普通  斤
2020-05-16  整牛  30.00  30.50  31.00   普通  斤
2020-05-17  整牛  30.00  30.50  31.00   普通  斤
2020-05-18  整牛  30.50  30.75  31.00   普通  斤
2020-05-19  整牛  30.50  30.75  31.00   普通  斤
...         ..    ...    ...    ...  ... ..

2021-05-12  整牛  34.00  34.00  34.00  牛肉类  斤
2021-05-13  整牛  34.00  34.00  34.00  牛肉类  斤
2021-05-14  整牛  34.25  34.25  34.25  牛肉类  斤
2021-05-15  整牛  34.25  34.25  34.25  牛肉类  斤
2021-05-16  整牛  34.25  34.25  34.25  牛肉类  斤

[250 rows x 6 columns]

发现明明有一年的数据,却只有250行,先保存下来再看看

import pandas as pd

output_file = 'vage.csv'
vege_data = pd.read_csv('vegetables.csv', header=None, index_col=6).sort_index()

new_data = vege_data[vege_data[0] == '整牛']

new_data.to_csv(output_file, header=False, encoding='utf-8')

matplotlib数据可视化三分钟入门,半小时入魔?
观察时发现中间有一段时间是没有价格的
matplotlib数据可视化三分钟入门,半小时入魔?
所以取2020-09-30这个时间段之后的数据
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = pd.read_csv('vage.csv', header=None)[29:]
print(data)

              0   1      2      3      4    5  6
29   2020-09-30  整牛  34.00  34.00  34.00   普通  斤
30   2020-10-01  整牛  34.00  34.00  34.00   普通  斤
31   2020-10-02  整牛  33.00  33.50  34.00   普通  斤
32   2020-10-03  整牛  33.00  33.50  34.00   普通  斤
33   2020-10-04  整牛  33.00  33.50  34.00   普通  斤
..          ...  ..    ...    ...    ...  ... ..

245  2021-05-12  整牛  34.00  34.00  34.00  牛肉类  斤
246  2021-05-13  整牛  34.00  34.00  34.00  牛肉类  斤
247  2021-05-14  整牛  34.25  34.25  34.25  牛肉类  斤
248  2021-05-15  整牛  34.25  34.25  34.25  牛肉类  斤
249  2021-05-16  整牛  34.25  34.25  34.25  牛肉类  斤

[221 rows x 7 columns]

Process finished with exit code 0

3,对’整牛’价格绘制折线图

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = pd.read_csv('vage.csv', header=None)[29:]

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

x = data[0]
y = data[3]

plt.figure(figsize=(12, 8))
plt.plot(x, y, '-r', lw=2, label='价格')
plt.legend()
plt.xlabel('时间/天', c='b', size=13)
plt.ylabel('单价/元', c='b', size=13)
plt.title('整牛价格折线图', c='g', size=20)
plt.ylim(32, 36)
plt.xticks(np.arange(0, 220, 8), rotation=45)
plt.show()

matplotlib数据可视化三分钟入门,半小时入魔?

Original: https://blog.csdn.net/hpl980342791/article/details/116893452
Author: 骑着哈哥去旅行
Title: matplotlib数据可视化三分钟入门,半小时入魔?

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/767216/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 彻底学会Selenium元素定位

    转载请注明出处❤️ 作者:测试蔡坨坨 原文链接:caituotuo.top/63099961.html 你好,我是测试蔡坨坨。 最近收到不少初学UI自动化测试的小伙伴私信,对于元素…

    Python 2023年10月18日
    026
  • Metasploit渗透框架介绍及永恒之蓝复现

    Metasploit渗透框架介绍及永恒之蓝复现 一、Metasploit渗透框架介绍 * 1.1 名词解释 1.2 MSF简介 1.3 MSF框架结构 1.4 MSF命令汇总 &#…

    Python 2023年11月5日
    039
  • Django动态展示Pyecharts图表数据

    注意: 以下示例是pyecharts官网django示例中的例子,目前发现一处bug,示例3中的定时增量无法实现,我在下面代码中已经改好。 该动态展示的index.html模板中用…

    Python 2023年8月3日
    075
  • 【技术积累】Python基础知识【第一版】

    Python是一种高级、通用的编程语言,由Guido van Rossum于1989年创造。它被设计为易于阅读和理解,具有简洁的语法和强大的功能。Python支持面向对象、函数式和…

    Python 2023年11月9日
    031
  • Python趣味入门4:选择往往是最重要的-条件语句

    人生处处有选择,程序也有选择,为了让程序变得更加强壮,程序员必须考虑任何情况,上一篇了解到了如何使用Python来行顺序语句的编写,我们写了一个可以输入姓名的生日祝贺程序,今天我们…

    Python 2023年6月12日
    045
  • python之列表详解

    文章目录 * – 一.创建列表 – + 1.基于弱数据类型语言的定义 + 2.通过全局函数list()定义 + 3.创建空列表 – 二.访问列表…

    Python 2023年7月31日
    065
  • 论人类下一代语言的可能—8.1图灵机

    历史上,伴随数学的发展,计算工具也不断推陈出新。在上世纪的中叶,计算工具的发展迎来了历史性的突破,现代计算机出现了。 上世纪三十年代,英国数学家图灵(Alan Mathison T…

    Python 2023年10月15日
    051
  • 2022年安徽最新交安安全员考试模拟题及答案

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

    Python 2023年10月24日
    032
  • 这是你没见过的MindSpore 2.0.0 for Windows GPU版

    摘要:一文带你看看MindSpore 2.0.0 for Windows GPU版。 在看了MindSpore架构师王磊老师的帖子( )之后,本来张小白要源码编译MindSpore…

    Python 2023年10月29日
    038
  • 沁恒CH32V003(二): Ubuntu20.04 MRS和Makefile开发环境配置

    沁恒CH32V003F4P6开发板 WCH-LinkE 使用 MounRiver Studio Community IDE 进行开发是比较简单的一种方式, 前往 http://mo…

    Python 2023年10月16日
    043
  • Pandas系列(三):数据清洗

    Pandas系列目录 文章目录 一、 简介 二、 思维导图 三、 Pandas数据清洗 * 1. 空值、缺失值处理 – 1.1 空值、缺失值判断 1.2 空值处理 2….

    Python 2023年8月19日
    055
  • python基础-模块和包

    包就是一个文件夹,里面放着一个个py文件或子包; 在包中可以被调用的一个个py文件,我们叫做模块; 如上,test就是一个包、two.py就是test下的一个模块,child是子包…

    Python 2023年10月30日
    037
  • 【Plotly】python数据可视化神器——绘制折线图

    Plotly简介 Plotly是用于机器学习、数据挖掘等领域的数据可视化包。 其图标视觉效果简洁大气,可互动性强,成为我工作中进行数据可视化的一大利器,接下来我们就从最简单的折线图…

    Python 2023年8月3日
    062
  • pandas—pd.merge通过键来联接数据集

    文章目录 * – + 根据连接键进行合并 + 根据索引合并 官方文档 《利用python进行数据分析》数据规整 根据连接键进行合并 合并或连接操作通过一个或者几个键连接…

    Python 2023年8月8日
    049
  • 使用jupyter中的matplotlib库绘制简单图表6、7

    1、 axis()函数隐藏轴脊 1.1隐藏全部轴脊 import numpy as np import matplotlib.pyplot as plt import matplo…

    Python 2023年9月1日
    061
  • Pandas案例精进 | 药品发放汇总与Excel表数据回填

    小小明:「凹凸数据」专栏作者,Pandas数据处理高手,致力于帮助无数数据从业者解决数据处理难题。 Pandas案例需求 有一个卫生院需要统计一下每个村扶贫药品发放的数据。 数据形…

    Python 2023年8月7日
    058
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球