Matplotlib数据分析基础
概要
本博客总结了matplotlib常见的数据分析工具使用方法,包括画折线图,柱状图,直方图,散点图等。
matplotlib.pyplot.plot绘制折线图
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import matplotlib
# 1. 中文字体设置
font = {
'family': 'Microsoft Yahei', 'size': '14'}
matplotlib.rc('font', **font) # 字体设置
# 2. 设置图片基本情况
fig = plt.figure(figsize=(20, 8), dpi=60) # 设置图片size和分辨率
plt.grid(alpha=0.5, linestyle='--') # 设置图片网格透明度和线型
plt.title("气温变化情况") # 图片标题
# 3. 给出坐标点并画图线
x = range(2, 26, 2) # 横坐标点列
y = [15, 14, 13, 14.5, 17, 20, 25, 26, 26, 22, 18, 15] # 纵坐标点列
y1 = [16, 14, 10, 10, 14, 18, 22, 22, 27, 26, 26, 25] # 纵坐标点列
plt.plot(x, y, label='北京',color ="cyan") # 根据(x,y)画散点图折线图,label为图例显示的字符
plt.plot(x, y1, label='上海', color="red", marker='*', linestyle='-.') # 画两个图
# 4. 设置刻度和标签
_xtick_labels = ["{} 天".format(i) for i in x] # 对x轴显示刻度进行修饰,2 day 4 day 6 day
plt.xticks(x[::2], _xtick_labels[::2], rotation=45) # plt.xticks(list, list(str), rotation)
plt.yticks(range(min(y1), max(y1))) # 设置y轴显示的刻度,表示密集程度
plt.xlabel("时间")
plt.ylabel("温度 单位(℃)")
# 5. 设置图例
plt.legend(loc=4) # 显示图例,即plt.plot中的label。loc表示图例的location
# 6. 保存图片
plt.savefig("./sig_size.svg") # 保存图片,给出位置和格式
# 7. 显示图片
plt.show()
matplotlib.pyplot.bar绘制条形图
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
from matplotlib import font_manager
# 1. 设置字体
my_font = font_manager.FontProperties(fname='C:\Windows\Fonts\simkai.ttf')
# 2. 图像大小和分辨率
plt.figure(figsize=(12, 8), dpi=80)
# 3. 电影票房数据数组
x = ['少年的你', '终结者:黑暗命运',