python数据分析学习

python数据分析学习

  • pandas操作json文件(Python语言)
import pandas as pd
import json
def analysis(file, user_id):
    with open(file, 'r') as f:
        if not f:
            return 0
        df = pd.read_json(f, orient='records')
        dfs = df[df['user_id'] == user_id]
        times = dfs.shape[0]
        minutes = dfs['minutes'].sum()
    return times, minutes
if __name__ == '__main__':
    result = analysis('user_study.json', 199071)
    print(result)
  • 可视化matplotlib
plt.show()
from matplotlib import pyplot as plt
plt.plot([1, 2, 3, 2, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1])
plt.plot([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],[1,2,3,3,4,2,32,2,1,2,1,21,2,1,4])

方法 含义
matplotlib.pyplot.angle_spectrum 绘制电子波谱图
matplotlib.pyplot.bar 绘制柱状图
matplotlib.pyplot.barh 绘制直方图
matplotlib.pyplot.broken_barh 绘制水平直方图
matplotlib.pyplot.contour 绘制等高线图
matplotlib.pyplot.errorbar 绘制误差线
matplotlib.pyplot.hexbin 绘制六边形图案
matplotlib.pyplot.hist 绘制柱形图
matplotlib.pyplot.hist2d 绘制水平柱状图
matplotlib.pyplot.pie 绘制饼状图
matplotlib.pyplot.quiver 绘制量场图
matplotlib.pyplot.scatter 散点图
matplotlib.pyplot.specgram 绘制光谱图
绘制正弦

import numpy as np
X=np.linspace(-2*np.pi,2*np.pi,1000)
y=np.sin(X)
plt.plot(X,y)
#柱状图
plt.bar([1, 2, 3], [1, 2, 3])
#二维图
plt.scatter(X, y)
#饼状图
plt.pie([1, 2, 3, 4, 5])
#向量图
X, y = np.mgrid[0:10, 0:10]
plt.quiver(X, y)
#等高线图
x=np.linspace(-5,5,500)
y=np.linspace(-5,5,500)
X,Y=np.meshgrid(x,y)
Z=(1-X/2+X**3+Y**4)*np.exp(-X**2-Y**2)
plt.contourf(X,Y,Z)

官网
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html

# 在 -2PI 和 2PI 之间等间距生成 1000 个值,也就是 X 坐标
X = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
# 计算 sin() 对应的纵坐标
y1 = np.sin(X)
# 计算 cos() 对应的纵坐标
y2 = np.cos(X)

# 向方法中 `*args` 输入 X,y 坐标
plt.plot(X, y1, color='r', linestyle='--', linewidth=2, alpha=0.8)
plt.plot(X, y2, color='b', linestyle='-', linewidth=2)
# 生成随机数据
x = np.random.rand(100)
y = np.random.rand(100)
colors = np.random.rand(100)
size = np.random.normal(50, 60, 10)

plt.scatter(x, y, s=size, c=colors)  # 绘制散点图
label = 'Cat', 'Dog', 'Cattle', 'Sheep', 'Horse'  # 各类别标签
color = 'r', 'g', 'r', 'g', 'y'  # 各类别颜色
size = [1, 2, 3, 4, 5]  # 各类别占比
explode = (0, 0, 0, 0, 0.2)  # 各类别的偏移半径
# 绘制饼状图
plt.pie(size, colors=color, explode=explode,
        labels=label, shadow=True, autopct='%1.1f%%')
# 饼状图呈正圆
plt.axis('equal')

定义图形的位置

x = np.linspace(0, 10, 20)  # 生成数据
y = x * x + 2

fig = plt.figure()  # 新建图形对象
axes = fig.add_axes([0.5, 0.5, 0.8, 0.8])  # 控制画布的左, 下, 宽度, 高度
axes.plot(x, y, 'r')
#or
fig=plt.figure()
a1=fig.add_axes([0.1,0.1,0.8,0.8])
a2=fig.add_axes([0.2,0.5,0.4,0.3])
a1.plot(x,y,'r')
a2.plot(y,x,'g')

plt.subplots()实现子图的绘制

fig, axes = plt.subplots(nrows=1, ncols=2)  # 子图为 1 行,2 列
for ax in axes:
    ax.plot(x, y, 'r')

添加图标题、坐标轴

fig, axes = plt.subplots()

axes.set_xlabel('x label')  # 横轴名称
axes.set_ylabel('y label')
axes.set_title('title')  # 图形名称

axes.plot(x, x**2)
axes.plot(x, x**3)
axes.legend(["y = x**2", "y = x**3"], loc=0)  # 图例

线型可供选择

fig, ax = plt.subplots(figsize=(12, 6))

# 线宽
ax.plot(x, x+1, color="blue", linewidth=0.25)
ax.plot(x, x+2, color="blue", linewidth=0.50)
ax.plot(x, x+3, color="blue", linewidth=1.00)
ax.plot(x, x+4, color="blue", linewidth=2.00)

# 虚线类型
ax.plot(x, x+5, color="red", lw=2, linestyle='-')
ax.plot(x, x+6, color="red", lw=2, ls='-.')
ax.plot(x, x+7, color="red", lw=2, ls=':')

# 虚线交错宽度
line, = ax.plot(x, x+8, color="black", lw=1.50)
line.set_dashes([5, 10, 15, 10])

# 符号
ax.plot(x, x + 9, color="green", lw=2, ls='--', marker='+')
ax.plot(x, x+10, color="green", lw=2, ls='--', marker='o')
ax.plot(x, x+11, color="green", lw=2, ls='--', marker='s')
ax.plot(x, x+12, color="green", lw=2, ls='--', marker='1')

# 符号大小和颜色
ax.plot(x, x+13, color="purple", lw=1, ls='-', marker='o', markersize=2)
ax.plot(x, x+14, color="purple", lw=1, ls='-', marker='o', markersize=4)
ax.plot(x, x+15, color="purple", lw=1, ls='-',
        marker='o', markersize=8, markerfacecolor="red")
ax.plot(x, x+16, color="purple", lw=1, ls='-', marker='s', markersize=8,
        markerfacecolor="yellow", markeredgewidth=2, markeredgecolor="blue")

画布网格或调整坐标轴范围

fig, axes = plt.subplots(1, 2, figsize=(10, 5))

# 显示网格
axes[0].plot(x, x**2, x, x**3, lw=2)
axes[0].grid(True)

# 设置坐标轴范围
axes[1].plot(x, x**2, x, x**3)
axes[1].set_ylim([0, 60])
axes[1].set_xlim([2, 5])

散点图、梯步图、条形图、面积图

n = np.array([0, 1, 2, 3, 4, 5])

fig, axes = plt.subplots(1, 4, figsize=(16, 5))

axes[0].scatter(x, x + 0.25*np.random.randn(len(x)))
axes[0].set_title("scatter")

axes[1].step(n, n**2, lw=2)
axes[1].set_title("step")

axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5)
axes[2].set_title("bar")

axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5)
axes[3].set_title("fill_between")

对柱形图进行文字标注

fig, axes = plt.subplots()

x_bar = [10, 20, 30, 40, 50]  # 柱形图横坐标
y_bar = [0.5, 0.6, 0.3, 0.4, 0.8]  # 柱形图纵坐标
bars = axes.bar(x_bar, y_bar, color='blue', label=x_bar, width=2)  # 绘制柱形图
for i, rect in enumerate(bars):
    x_text = rect.get_x()  # 获取柱形图横坐标
    y_text = rect.get_height() + 0.01  # 获取柱子的高度并增加 0.01
    plt.text(x_text, y_text, '%.1f' % y_bar[i])  # 标注文字
   # 增加箭头标注
    plt.annotate('Min', xy=(32, 0.3), xytext=(36, 0.3),
                 arrowprops=dict(facecolor='black', width=1, headwidth=7))
   #上面的示例中,xy=() 表示标注终点坐标,xytext=() 表示标注起点坐标。在箭头绘
   #制的过程中,arrowprops=() 用于设置箭头样式,facecolor= 设置颜色,width= 
   #设置箭尾宽度,headwidth= 设置箭头宽度,可以通过 arrowstyle= 改变箭头的样式。
   

兼容matlab

from matplotlib import pylab
x = np.linspace(0, 10, 20)
y = x * x + 2
pylab.plot(x, y, 'r')  # 'r' 代表 red
pylab.subplot(1, 2, 1)  # 括号中内容代表(行,列,索引)
pylab.plot(x, y, 'r--')  # ‘’ 中的内容确定了颜色和线型

pylab.subplot(1, 2, 2)
pylab.plot(y, x, 'g*-')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值