Python数据分析第7天

Python数据分析第07天

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

plt.rcParams['font.sans-serif'] = ['FangSong']
plt.rcParams['axes.unicode_minus'] = False
%config InlineBackend.figure_format = 'svg'


plt.figure(figsize=(8,6),dpi=120)
plt.subplot(2,1,1)
plt.subplot(2,1,2)


在这里插入图片描述
在这里插入图片描述

数据可视化

  1. Matplotlib —> 画图给自己看,用于数据探索

    • 画布 —> figure() —> Figure
    • 坐标系 —> subplot() —> 一个画布上可以有多个坐标系 —> Axes
    • 坐标轴 —> plot() / scatter() / bar() / pie() / hist() / box()
      • 趋势 —> 折线图
      • 关系 —> 散点图
      • 差异 —> 柱状图
      • 占比 —> 饼图
      • 分布 —> 直方图
      • 描述性统计信息 —> 箱线图(盒须图)
  2. Seaborn —> 对Matplotlib做了封装,用默认的配置减少绘图参数

  3. ECharts / D3.js —> 商业数据看板 / 数字化大屏 —> 前端JavaScript绘图库

    • 后端程序:提供绘图需要使用的数据(API接口)—> 数据的服务化 —> Java / PHP / Python
    • 前端程序:通过HTTP获取数据,用JavaScript将数据渲染到网页上
    • –> PyECharts

    在这里插入图片描述
    在这里插入图片描述

# 折线图和散点图
x = np.linspace(-2 * np.pi, 2 * np.pi, 60)
y1, y2 = np.sin(x), np.cos(x)
y3, y4 = np.sin(x), np.cos(x)

# 创建画布 ---> figure函数会返回Figure对象
# fig = plt.figure(...)
plt.figure(figsize=(8, 6), dpi=120)

# 创建坐标系 ---> subplot函数会返回Axes对象
# ax = fig.add_subplot(2, 2, 1)
plt.subplot(2, 2, 1)
# 调用plot函数绘制折线图,如果之前没有创建画布,在调用plot时会自动用默认设置创建画布
# ax.plot(...)
plt.plot(x, y1, marker='x', color='#ff00ff', linestyle=':', linewidth=1)
# 横轴和纵轴的标签
plt.xlabel(r'$ \alpha $')
plt.ylabel(r'$ y = sin(\alpha) $')
# 图的标题
plt.title('正弦曲线')

ax = plt.subplot(2, 2, 2)
# 修改坐标轴的位置和显示方式
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_position(('data', 0.0))
ax.spines['bottom'].set_position(('data', 0.0))
# 定制x和y轴的可读
plt.xticks(
    np.arange(-2 * np.pi, 2 * np.pi + 1, np.pi / 2),
    labels=[r'$-2\pi$', r'$-\frac{3}{2}\pi$', r'$-\pi$', r'$-\frac{\pi}{2}$', '0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3}{2}\pi$', r'$2\pi$']
)
plt.yticks(np.arange(-1, 1.1, 0.5))
plt.plot(x, y2, marker='.', color='#00ffff', linestyle='-', linewidth=2)

plt.subplot(2, 1, 2)
# 调用scatter函数绘制散点图
plt.scatter(x, y3, s=x ** 2, c=y3, cmap='Reds', label='正弦')
plt.scatter(x, y4, s=(y4 * 15 + 20), c=y4, cmap='Greens', label='余弦')
# 在图上添加注释
plt.annotate('正弦曲线', xy=(0.1, 0.2), xytext=(1, -0.8), arrowprops={
    'facecolor': 'blue', 'arrowstyle': '->', 'edgecolor': 'blue',
    'connectionstyle': 'angle3,angleA=0,angleB=90'
})

# 添加图例
plt.legend(loc='lower right')

# 保存图像
plt.savefig('result.png')
# 显示图像
plt.show()

在这里插入图片描述
在这里插入图片描述

# 饼图
plt.figure(figsize=(4, 4), dpi=120)
data = np.random.randint(100, 500, 5)
print(data)
labels = ['苹果', '香蕉', '桃子', '荔枝', '石榴']
plt.pie(
    data,
    autopct='%.1f%%',
    radius=1,
    pctdistance=0.8,
    # explode=[0.1, 0, 0.2, 0, 0],
    # shadow=True,
    # 字体属性
    # textprops=dict(fontsize=8, color='black'),
    textprops={'fontsize': 8, 'color': 'black'},
    # 楔子属性
    wedgeprops=dict(linewidth=1, width=0.35, edgecolor='white'),
    labels=labels
)
plt.show()

# 柱状图
labels = np.array(['Q1', 'Q2', 'Q3', 'Q4'])
group1 = np.random.randint(20, 50, 4)
print(group1)
group2 = np.random.randint(10, 60, 4)
print(group2)
group3 = np.random.randint(30, 40, 4)
print(group3)
plt.bar(labels, group1, 0.6, label='销售A组')
# 通过bottom属性设置数据堆叠
plt.bar(labels, group2, 0.6, bottom=group1, label='销售B组')
plt.bar(labels, group3, 0.6, bottom=group1 + group2, label='销售C组')
plt.legend()
plt.show()

在这里插入图片描述

width = 0.2
x = np.arange(labels.size)
plt.bar(x - width, group1, width, label='销售A组')
plt.bar(x, group2, width, label='销售B组')
plt.bar(x + width, group3, width, label='销售C组')
plt.xticks(x, labels=labels)
plt.legend(loc='lower right')
plt.show()

在这里插入图片描述

面积图

plt.figure(figsize=(6, 3))
days = np.arange(7)
sleeping = [7, 8, 6, 6, 7, 8, 10]
eating = [2, 3, 2, 1, 2, 3, 2]
working = [7, 8, 7, 8, 6, 2, 3]
playing = [8, 5, 9, 9, 9, 11, 9]
plt.stackplot(days, sleeping, eating, working, playing)
plt.legend(['睡觉', '吃饭', '工作', '玩耍'], fontsize=10)
plt.show()

在这里插入图片描述

# 雷达图(极坐标折线图)

labels = np.array(['专业技能', '工作经验', '团队意识', '沟通能力', '学习能力'])
values = np.array([78, 85, 95, 72, 88])
angles = np.linspace(0, 2 * np.pi, labels.size, endpoint=False)

# 加一条数据让图形闭合

values = np.concatenate((values, [values[0]]))
angles = np.concatenate((angles, [angles[0]]))
plt.figure(figsize=(4, 4), dpi=120)
ax = plt.subplot(projection='polar')

# 绘图和填充

plt.plot(angles, values, marker='o', linestyle='--', linewidth=2)
plt.fill(angles, values, alpha=0.25)

# 设置文字和网格线

ax.set_thetagrids(angles[:-1] * 180 / np.pi, labels, fontsize=10)
ax.set_rgrids([20, 40, 60, 80], fontsize=10)
plt.show()

在这里插入图片描述

# 玫瑰图(圆形柱状图)
x = np.array([f'A-Q{i}' for i in range(1, 5)] + [f'B-Q{i}' for i in range(1, 5)])
y = np.array(group1.tolist() + group2.tolist())
print(y)
theta = np.linspace(0, 2 * np.pi, x.size, endpoint=False)
width = 2 * np.pi / x.size
colors = np.random.rand(8, 3)
# 将柱状图投影到极坐标
ax = plt.subplot(projection='polar')
plt.bar(theta, y, width=width, color=colors, bottom=0)
ax.set_thetagrids(theta * 180 / np.pi, x, fontsize=10py
plt.show()

在这里插入图片描述

plt.figure(figsize=(8, 4), dpi=120)
ax = plt.subplot(projection='3d')

colors = ['r', 'g', 'b']
yticks = range(2020, 2017, -1)
for idx, y in enumerate(yticks):
    x_data = [f'{x}季度' for x in '一二三四']
    z_data = np.random.randint(100, 600, 4)
    ax.bar(x_data, z_data, zs=y, zdir='y', color=colors[idx], alpha=0.5)
ax.set_xlabel('季度')
ax.set_ylabel('年份')
ax.set_zlabel('销量')
ax.set_yticks(yticks)
plt.show()

度’ for x in ‘一二三四’]
z_data = np.random.randint(100, 600, 4)
ax.bar(x_data, z_data, zs=y, zdir=‘y’, color=colors[idx], alpha=0.5)
ax.set_xlabel(‘季度’)
ax.set_ylabel(‘年份’)
ax.set_zlabel(‘销量’)
ax.set_yticks(yticks)
plt.show()


![在这里插入图片描述](https://img-blog.csdnimg.cn/e55622dcfa4d48d98efe448b9130f88b.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6Zuq55CD5rua5rua5rua,size_19,color_FFFFFF,t_70,g_se,x_16#pic_center)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值