matplot.pyplot 绘制图像 回顾

本文介绍了如何使用Python的pandas库进行数据按年月汇总统计,包括转换日期格式、分组计数和绘制柱状图。通过实例展示了如何利用groupby函数对DataFrame数据进行分组,并绘制柱状图展示不同年份和月份的频次。同时,还探讨了饼图的制作,提供了一种展示数据分布的方式。内容涵盖了数据处理和可视化的基本技巧,适合Python数据分析初学者参考。
摘要由CSDN通过智能技术生成

按年月进行计数,汇总例子

导包

import pandas as pd
import matplotlib.pyplot as plt

读取数据

path = r'C:\Users\Administrator\Desktop\42numbers.xls'

查看数据

data

在这里插入图片描述
这里选择 某一列 的时间进行,进行汇总统计
统计出 不同 年份 不同月份 的数量
然后 绘制 柱状图/饼图

首先 以 年月 进行 汇总 统计

df = data
data_new = df.groupby([df["sell_date"].dt.year, df["sell_date"].dt.month]).count()

小tips:

pd.groupby(
by=None, 
axis=0,  # 恒坐标还是纵坐标,默认位 index横坐标
level=None, 
as_index=True, 
sort=True, 
group_keys=True,
 squeeze=NoDefault.no_default, 
 observed=False, 
 dropna=True)

举例子:

df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
                              'Parrot', 'Parrot'],
                   'Max Speed': [380., 370., 24., 26.]})

df
Animal Max Speed
0 Falcon 380.0
1 Falcon 370.0
2 Parrot 24.0
3 Parrot 26.0

df.groupby(['Animal']).mean()
        Max Speed

Animal
Falcon 375.0
Parrot 25.0

默认是根据index即行进行分组

arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
          ['Captive', 'Wild', 'Captive', 'Wild']]
index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},
                  index=index)
df
这里level 就是根据index进行分类,
这个数据共有外内两个索引 index,
 外Animal 
 内 Type
            Max Speed

Animal Type
Falcon Captive 390.0
Wild 350.0
Parrot Captive 30.0
Wild 20.0


外索引,  level = 0

df.groupby(level=0).mean()

        Max Speed
Animal
Falcon      370.0
Parrot       25.0


内索引 level = '内索引的名字'
就是说 通过 数字 or 名字, 两者 都可以 对数据进行分组.

df.groupby(level=“Type”).mean()

         Max Speed
Type
Captive      210.0
Wild         185.0
l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]]
df = pd.DataFrame(l, columns=["a", "b", "c"])
df
 a     b      c
 1     2      3
 1   None  4
 1     2       2

根据 b 列进行分组

df.groupby(by=["b"]).sum()
a   c

b
1.0 2 3
2.0 2 5

默认会去掉 Nan的那一组, 当然也可以将这一列分组显示出来

df.groupby(by=["b"], dropna=False).sum()

a c
b
1.0 2 3
2.0 2 5
NaN 1 4

返回 例子
这里是根据 年 月 的,进行统计数的分组

data_new = df.groupby([df["sell_date"].dt.year, df["sell_date"].dt.month]).count()

在这里插入图片描述

这里选择对 sell_date进行柱状图的统计

data['sell_date'] =  data['sell_date'].astype("datetime64") # 首先将这列转为 时间格式
df = data[['sell_date']] # df 存储这列
df.groupby([df["sell_date"].dt.year, df["sell_date"].dt.month]).count().plot(kind="bar") # 分组计数绘制 柱状图
plt.yticks([1,2,3,4,5,6]) # 设置 y轴的每一列的数
plt.xticks(rotation=45) # 设置x轴 下面字体 旋转45度
plt.xlabel('sell_date') # 设置 x轴 名字
plt.grid() # 背景增加网格

在这里插入图片描述

设置饼图的数据

pie = []
for i in data_new['month_count']:
    pie.append(i)

在这里插入图片描述

设置饼图每个数据的对应标签名

label=[]
for a in data_new.index:
    a = str(a[0])+'年'+str(a[1])+'月'
    label.append(a)

在这里插入图片描述
饼图参数

pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, hold=None)
 x:饼状图的块数,及每块的值
explode:对应的块偏离圆心的比例
labels:每块表示的内容
colors:也是数组,表示每块内容的颜色,设置为None则系统自动分配颜色
autopct:表示显示每块所占的比例
pctdistance=0.8:百分比距中心的距离比例
shadow=True:是否有阴影效果
labeldistance:表示每块对应内容文字距离中心点是饼图半径的倍数
startangle=90 起始绘制角度,并且是逆时针绘制
radius:饼状图的半径,默认是1  hold:是否覆盖其他图形,如果在一个figure中绘制,选择True会覆盖,False会共存
plt.rcParams['font.sans-serif']=['Simhei'] # 保证饼图可以显示中文


plt.figure(figsize=(20,20)) # 设置画布的大小


patches,l_text,p_text = plt.pie(pie,
labels=label,
autopct='%1.1f%%',
startangle=0,
shadow=False,
pctdistance=0.8)
plt.legend(loc="upper right",fontsize=15,bbox_to_anchor=(1.1,1.05),borderaxespad=0.3)

# 设置饼图字体大小
for t in l_text:
    t.set_size(15)
for t in p_text:
    t.set_size(20)
# 保存饼图
# plt.savefig("C:\\饼图02.png",dpi=200,bbox_inches='tight')  

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值