数据分析——matplotlab

本文详细介绍了使用Python的Matplotlib库进行2D绘图的方法,包括折线图、散点图、条形图、直方图等图表的绘制,以及如何设置标题、轴标签、图例、网格和子图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是matplotlsb
Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形 。
通过 Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。

绘制折线图

import  random
from matplotlib  import  pyplot as plt


#
x = range(2,26,2)
y = [random.randint(10,30) for i in range(12)]

#设置图片的大小,dpi: 设置图片的清晰度
plt.figure(figsize=(20,8), dpi= 100)
#传递 x, y 值
plt.plot(x,y)

#x轴和y轴显示的范围
plt.xticks(x[:])
plt.yticks(range(min(y),max(y) +1))
# plt.show()
plt.savefig("./hello.png" , dpi = 100)

运行结果为:
在这里插入图片描述

设置坐标轴的含义

import random
from matplotlib import pyplot as plt, font_manager
import matplotlib

#  fc-list  :lang=zh  =====> 列出电脑上所有的中文字体库
myfont = font_manager.FontProperties(fname="/usr/share/fonts/wqy-microhei/wqy-microhei.ttc", size=12)
titlefont = font_manager.FontProperties(fname="/usr/share/fonts/wqy-microhei/wqy-microhei.ttc", size=32, weight=True)

y = [random.randint(20, 35) for i in range(120)]
x = range(0, 120)
plt.figure(figsize=(10, 5), dpi=100)
plt.plot(x, y)


plt.xlabel("时间", fontproperties=myfont)
plt.ylabel("温度(摄氏度)", fontproperties=myfont)
plt.title("10点到12点每分钟时间的时间变化情况", fontproperties=titlefont)
plt.show()
plt.savefig('./hello.png')

运行结果为:
在这里插入图片描述

绘制线性函数

import  numpy as np
from matplotlib import  pyplot as plt

x = np.arange(1,11)
y1 = x+5
y2 = x**2 +5
y3 = x**3  +5

# 设置标题,x轴,y轴的含义
plt.title('Matplotlib')
plt.xlabel('x')
plt.ylabel('y')

# “o” 代表圆点,“b” 代表蓝色
plt.plot(x,y1 , 'ob')
plt.plot(x,y2)
plt.plot(x,y3)
plt.show()

运行结果为:
在这里插入图片描述

绘制正弦函数

import  numpy as np
from matplotlib import pyplot as plt

# np.arange([start, ]stop, [step, ]dtype=None): arange函数用于创建等差数组
"""
start:可忽略不写,默认从0开始;起始值
stop:结束值;生成的元素不包括结束值
step:可忽略不写,默认步长为1;步长
dtype:默认为None,设置显示元素的数据类型
"""
x = np.arange(0,3*np.pi,0.01)
y = np.sin(x)

plt.title("sin(x)")
plt.xlabel('x')
plt.ylabel('y')


plt.plot(x,y)
plt.show()

运行结果为:
在这里插入图片描述

绘制竖向子图

import numpy as np
import matplotlib.pyplot as plt

# 计算正弦和余弦曲线上的点的 x 和 y 坐标
x = np.arange(0,  3  * np.pi,  0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# 建立 subplot 网格,高为 2,宽为 1
# 激活第一个 subplot, 位于第一行
plt.subplot(2,  1,  1)
# 绘制第一个图像
plt.plot(x, y_sin)
plt.title('Sin(x)')
# 将第二个 subplot 激活,并绘制第二个图像, 位于第2行;
plt.subplot(2,  1,  2)
plt.plot(x, y_cos)

plt.title('Cos(x)')
# 展示图像
plt.show()

运行结果为:
在这里插入图片描述

绘制横向子图

    import numpy as np
    import matplotlib.pyplot as plt
    
    # 计算正弦和余弦曲线上的点的 x 和 y 坐标
    x = np.arange(0,  3  * np.pi,  0.1)
    y_sin = np.sin(x)
    y_cos = np.cos(x)
    
    plt.figure(figsize=(30, 10), dpi=100)
    # 建立 subplot 网格,高为 2,宽为 1
    # 激活第一个 subplot, 位于第一行
    plt.subplot(2,  2,  1)
    # 绘制第一个图像
    plt.plot(x, y_sin)
    plt.title('Sin(x)')
    # 将第二个 subplot 激活,并绘制第二个图像, 位于第2行;
    plt.subplot(2,  2, 4)
    plt.plot(x, y_cos)
    
    plt.title('Cos(x)')
    # 展示图像
    plt.show()


运行结果为:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190826115120742.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0ZhbmN5eWo=,size_16,color_FFFFFF,t_70)

添加网格和图例
import numpy as np
import matplotlib.pyplot as plt

# 设置x和y
x = np.arange(1, 11)  # [1, 2, 3,.....10]
y1 = x + 5
y2 = x ** 2 + 5
y3 = x ** 3 + 5

# 设置标题, x周和y轴含义
plt.title("Matplotlib demo")
plt.xlabel("x")
plt.ylabel("y")


# label是一个子图多条图像时,设置的图例名称;
plt.plot(x, y1, 'ob', label='y=x+5')  # 'o'代表圆点, ‘b’颜色, 蓝色blue
plt.plot(x, y2, "*y", label='y=x**2+5')
plt.plot(x, y3, label='y=x**3+5')

# 设置图例位置
plt.legend(loc="upper left")

# # 添加网格
plt.grid(alpha=0.1)

plt.show()

运行结果为:
在这里插入图片描述

绘制散点图

import random
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties
"""
绘制10月和三月温度变化的散点图
"""

# 字体设置
myfont = FontProperties(fname="/usr/share/fonts/wqy-microhei/wqy-microhei.ttc", size=14)
titlefont = FontProperties(fname="/usr/share/fonts/wqy-microhei/wqy-microhei.ttc", size=25)

# x轴和Y轴数据
march_y = [random.randint(10, 20) for i in range(31)]
october_y = [random.randint(20, 30) for j in range(31)]
x = range(1, 32) # 1, 2, 3, ...31


# 设置图形大小
plt.figure(figsize=(10, 5), dpi=100)

# 绘制散点图
plt.subplot(2,  1,  1)
plt.scatter(x, march_y, )
# 调整刻度
_x3_labels = ["3月{}日".format(_) for _ in x]
# rotation: 旋转
plt.xticks(x[::3], labels=_x3_labels[::3], fontproperties=myfont, rotation=45)
# x, y和标题的说明
plt.xlabel("月份", fontproperties=myfont)
plt.ylabel("温度(摄氏度)", fontproperties=myfont)
plt.title("3月温度变化散点图", fontproperties=titlefont)

plt.subplot(2,  1,  2)
plt.scatter(x, october_y)
_x10_labels = ["10月{}日".format(_) for _ in x]
plt.xticks(x[::3], labels=_x10_labels[::3], fontproperties=myfont, rotation=45)
# x, y和标题的说明
plt.xlabel("月份", fontproperties=myfont)
plt.ylabel("温度(摄氏度)", fontproperties=myfont)
plt.title("10月温度变化散点图", fontproperties=titlefont)

# 添加网格
plt.grid(alpha=0.5)

# 显示图像
plt.show()调整刻度
_x3_labels = ["3月{}日".format(_) for _ in x]
# rotation: 旋转
plt.xticks(x[::3], labels=_x3_labels[::3], fontproperties=myfont, rotation=45)
# x, y和标题的说明
plt.xlabel("月份", fontproperties=myfont)
plt.ylabel("温度(摄氏度)", fontproperties=myfont)
plt.title("3月温度变化散点图", fontproperties=titlefont)

plt.subplot(2,  1,  2)
plt.scatter(x, october_y)
_x10_labels = ["10月{}日".format(_) for _ in x]
plt.xticks(x[::3], labels=_x10_labels[::3], fontproperties=myfont, rotation=45)
# x, y和标题的说明
plt.xlabel("月份", fontproperties=myfont)
plt.ylabel("温度(摄氏度)", fontproperties=myfont)
plt.title("10月温度变化散点图", fontproperties=titlefont)

# 添加网格
plt.grid(alpha=0.5)

# 显示图像
plt.show()

运行结果为:
在这里插入图片描述

绘制条形图

"""
bar(): pyplot 子模块提供 bar() 函数来生成条形图。
"""

from matplotlib import pyplot as plt

x = [5, 8, 10]
y = [12, 16, 6]
x2 = [6, 9, 11]
y2 = [6, 15, 7]
plt.bar(x, y, align='center')
plt.bar(x2, y2, color='g', align='center')

plt.title('Bar graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

运行结果为:
在这里插入图片描述

绘制直方图

import random
import matplotlib.pyplot as plt

names = ['电影%s' % (i) for i in range(100)]
times = [random.randint(40, 140) for i in range(100)]

# 如何实现数据的分组?   组数 = 极差 / 组距; 极差= max - min
#  数据为100个以内, 一般分为5~12组;

bin_width = 3  # 设置组距为3;
num_bins = (max(times) - min(times)) // bin_width  # 合理确定组数
print(num_bins)
# hist代表直方图, times为需要统计的数据, 20为统计的组数.
# plt.hist(times, num_bins)
# plt.hist(times, [min(times) + i * bin_width for i in range(num_bins)])
# normed: bool, 是否绘制频率分布直方图, 默认为频数直方图.
plt.hist(times, [min(times) + i * bin_width for i in range(num_bins)], normed=1)

# x轴的设置
plt.xticks(list(range(min(times), max(times)))[::bin_width], rotation=45)

# 设置网格
plt.grid(True, linestyle='-.', alpha=0.5)
plt.show()

运行结果为:
在这里插入图片描述

### 如何在 PyQt 中使用 Matplotlib 实现数据可视化 要在 PyQt 中实现基于 Matplotlib 的数据可视化功能,可以通过 `FigureCanvas` 和 `NavigationToolbar2QT` 来完成。以下是具体方法: #### 1. 创建一个基本的 PyQt 应用程序框架 通过继承 `QMainWindow` 或其他窗口类来构建应用程序的基础结构。 ```python from PyQt5.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QWidget import sys ``` #### 2. 嵌入 Matplotlib 图表区域 利用 `FigureCanvas` 类将 Matplotlib 图形嵌入到 PyQt 界面中。这一步骤允许开发者创建动态更新的图表并将其显示在 GUI 上。 ```python from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure class MplCanvas(FigureCanvas): def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) super(MplCanvas, self).__init__(fig) ``` 此部分代码定义了一个新的画布组件 `MplCanvas`,用于承载所有的绘图操作[^1]。 #### 3. 集成导航工具栏 (可选) 如果希望用户提供交互式的图表控制选项,则可以加入 Matplotlib 导航工具条。 ```python from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar toolbar = NavigationToolbar(canvas, MainWindow) layout.addWidget(toolbar) ``` 上述片段展示了如何向布局添加标准的 Matplotlib 工具栏[^2]。 #### 4. 绘制简单的折线图作为演示案例 下面给出一段完整的例子展示怎样在一个独立窗体里呈现一条随机生成的数据曲线。 ```python import numpy as np class MainWindow(QMainWindow): def __init__(self): super().__init__() sc = MplCanvas(self, width=5, height=4, dpi=100) n_data = 50 x = list(range(n_data)) y = [np.random.rand() * i for i in range(n_data)] sc.axes.plot(x, y) layout = QVBoxLayout() layout.addWidget(sc) widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) app = QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_()) ``` 这段脚本初始化了一张带有时间序列样式的简单直线型态图像,并把它放置于主窗口中央位置[^3]。 #### 总结说明 以上过程涵盖了从零搭建具备基础统计分析能力的应用软件所需的关键技术要点。借助这些技巧,程序员能够快速上手开发自己的专属数据分析平台。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值