天天看点

数学建模入门-python绘制频率直方图例题数据处理绘图操作调用演示

文章目录

  • 例题
  • 数据处理
  • 绘图操作
  • 调用演示

例题

数学建模入门-python绘制频率直方图例题数据处理绘图操作调用演示

数据处理

将以下的数据保存到磁盘上

172 75 169 55 169 64 171 65 167 47
171 62 168 67 165 52 169 62 168 65
166 62 168 65 164 59 170 58 165 64
160 55 175 67 173 74 172 64 168 57
155 57 176 64 172 69 169 58 176 57
173 58 168 50 169 52 167 72 170 57
166 55 161 49 173 57 175 76 158 51
170 63 169 63 173 61 164 59 165 62
167 53 171 61 166 70 166 63 172 53
173 60 178 64 163 57 169 54 169 66
178 60 177 66 170 56 167 54 169 58
173 73 170 58 160 65 179 62 172 50
163 47 173 67 165 58 176 63 162 52
165 66 172 59 177 66 182 69 175 75
170 60 170 62 169 63 186 77 174 66
163 50 172 59 176 60 166 76 167 63
172 57 177 58 177 67 169 72 166 50
182 63 176 68 172 56 173 59 174 64
171 59 175 68 165 56 169 65 168 62
177 64 184 70 166 49 171 71 170 59
           

读取数据的代码

def read_data():
    heights = []
    weights = []
    with open('datas/data1.txt') as f:			# 记得修改文件路径
        for row in f:
            count = 0
            for cell in row.strip().split(' '):
                if count % 2 == 0:
                    heights.append(cell)
                else:
                    weights.append(cell)
                count = count+1
        print(heights)
        print(weights)
    return heights, weights
           

绘图操作

需要注意的是上一步读取数据是无需的,绘图之前需要排序

注意

import matplotlib.pyplot as plt

def draw_pic(heights, weights):
    plt.rcParams['font.sans-serif'] = ['SimHei']				# 解决中文无法显示的问题
    plt.rcParams['axes.unicode_minus'] = False			# 用来正常显示负号
    plt.subplot(211)														# 2行1列第一幅图
    plt.hist(sorted(heights), bins=5)								# bins表示分为5条直方,可以根据需求修改
    plt.xlabel('身高')
    plt.ylabel('频数')
    plt.subplot(212)														# 2行2列第二幅图
    plt.hist(sorted(weights), density=True)					# density为True表示频率,否则是频数,可根据需求修改
    plt.xlabel('体重')
    plt.ylabel('频率')
    plt.show()
           

调用演示

if __name__ == '__main__':
    heights, weights = read_data()
    draw_pic(heights, weights)
           
数学建模入门-python绘制频率直方图例题数据处理绘图操作调用演示

继续阅读