Python数据分析(⼀)——matplotlib画折线图,直⽅图,柱状图和散点图Matplotlib数据分析基础
概要
本博客总结了matplotlib常见的数据分析⼯具使⽤⽅法,包括画折线图,柱状图,直⽅图,散点图等。
matplotlib.pyplot.plot绘制折线图
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import matplotlib
# 1. 中⽂字体设置
font ={'family':'Microsoft Yahei','size':'14'}
<('font',**font)# 字体设置
# 2. 设置图⽚基本情况
fig = plt.figure(figsize=(20,8), dpi=60)# 设置图⽚size和分辨率
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 icks(x[::2], _xtick_labels[::2], rotation=45)# icks(list, list(str), rotation)
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\f') # 2. 图像⼤⼩和分辨率
plt.figure(figsize=(12,8), dpi=80)
# 3. 电影票房数据数组
x =['少年的你','终结者:⿊暗命运','天⽓之⼦']# 电影名称
bar_width =0.2# 条线宽度,即蓝橙绿条都是0.2
x1 =list(range(len(x)))# [0, 1, 2, 3]  # 1⽇
x2 =[i+bar_width for i in x1]# [0.2, 1.2, 2.2, 3.2] # 2⽇
x3 =[i+bar_width*2for i in x1]# [0.4, 1.4, 2.4, 3.4]  # 3⽇
y1 =[7131,6319,4588]
y2 =[13453,7398,6621]
y3 =[9213,5497,4247]
# 4. 画图
plt.bar(x1, y1, width=bar_width, label="11⽉1⽇")
plt.bar(x2, y2, width=bar_width, label='11⽉2⽇')
plt.bar(x3, y3, width=bar_width, label='11⽉3⽇')
svg图# 5. 设置图例
plt.legend(prop=my_font)
# 6. 设置刻度
# 7. 显⽰图⽚
plt.show()
也可绘制⽔平⽅向的条形图,使⽤plt.barh
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
from matplotlib import font_manager
# 1. 设置字体
my_font = font_manager.FontProperties(fname='C:\Windows\f')
# 2. x和y轴数据
x =['少年的你','终结者:⿊暗命运','天⽓之⼦','我和我的祖国','中国机长','沉睡魔咒2','为国⽽歌','催眠·裁决','双⼦杀⼿','打过长江去'] y =[1084.14,739.63,605.48,221.73,103.65,88.02,43.52,41.03,29.35,25.06]
# 3. 图⽚⼤⼩和分辨率设置
plt.figure(figsize=(12,8), dpi=80)
# 4. 绘图
plt.barh(x, y, height=0.3, color='orange', label="票房统计")
# 5. 设置刻度和坐标轴
plt.xlabel(xlabel="票房", fontproperties=my_font, fontsize=18)
# 6. 设置⽹格
# 7. 保存图⽚
plt.savefig('./movie.png')
# 8. 显⽰图⽚
plt.show()