用matplotlib绘制体重变化十年趋势图

author: Quantified Bob

src: https://www.quantifiedbob.com/body-composition-data-visualization/

9ad3e5f62d12a3fdac4a5b4ce5a61a36.png

每天看到运动步数和消耗的热量,感觉心里有数。今天刚刚看到的一个博主Quantified Bob,数字化个人生理指标,通过历史数据更好的管理自我健康,历时十年的个人体重数据。通过这个案例,咱们可以学到

  • pandas语法,如填充缺失值、30日均值计算

  • matplotlib绘图,如何显示中文,加格子,图例,标题


使用 Jupyter Notebook/Python 可视化Bob 10 多年的身体成分(体重、体脂)数据。 

导入数据

import pandas as pd

df = pd.read_csv('data/bob_weights.csv', parse_dates= ["日期"])
#日期排序
df.sort_values("日期", ascending = True, inplace=True)
df.head()

23cd703f26833c9ff2429254743249d2.png


可视化

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib
%matplotlib inline
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

#显示中文
matplotlib.rc("font", family='Arial Unicode MS') 

# create weights chart
fig, ax = plt.subplots()
ax.margins(0.05) # optional, adds 5% padding to autoscaling

# plot weight data
colors=["deeppink", "green", "darkorange", "olive", "red", "teal"]


i=0
for key, grp in df.groupby(['数据源']):
    ax.scatter(grp['日期'], 
               grp['体重lb'], 
               s=16, 
               label=key, 
               alpha=0.5, 
               edgecolors='none', 
               color=colors[i])
    i = i + 1

# 缺失值填充 & 30日移动均值
df["体重lb"].fillna(method ='ffill', inplace = True)
rolling_mean = df["体重lb"].rolling(window=30).mean()


ax.plot(df["日期"], 
        rolling_mean, 
        label='30日均线', 
        color='rebeccapurple', 
        alpha=0.6, 
        linewidth=3)

# title and axes
# plt.subplots_adjust(top=0.85)
plt.title("Bob十年来的体重趋势", fontsize=16, fontweight='bold')

plt.xlabel('日期', fontsize=12, fontweight='bold')

plt.ylabel('体重(lb)', fontsize=12, fontweight='bold')
# display x-axis ticks for every year using YYYY format
years = mdates.YearLocator()
years_fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)

# legend and grid lines
ax.legend(loc='upper left', fontsize=16)
ax.grid(True)

# resize chart
#plt.rcParams['figure.figsize'] = (18.0, 16.0)
plt.rcParams['figure.figsize'] = (28.0, 13.0)

# save image
plt.savefig('chart-weights.png', bbox_inches='tight')

3bd516b85dd2667d359d687f1467e500.png

不同颜色表示每个数据源(可穿戴设备),趋势线为30天移动平均线。

代码下载

https://github.com/hidadeng/DaDengAndHisPython/tree/master/20211029用matplotlib绘制十年来体重变化趋势图

1d3cf76066a8f0ba6f8056330752eeee.png

 
 

近期文章

视频专栏课 | Python网络爬虫与文本分析

Shifterator库 | 词移图分辨两文本用词风格差异

建议收藏 | nltk和spacy配置方法

DataShare | 6000+个股票的每日财经新闻  
SmartScraper | 简单、自动、快捷的Python网络爬虫
SHAP | 机器学习模型解释库

读完本文你就了解什么是文本分析

文本分析在经管领域中的应用概述

综述:文本分析在市场营销研究中的应用

文本分析方法在《管理世界》(2021.5)中的应用
中文金融情感词典发布啦 | 附代码
wordexpansion包 | 新增词向量法构建领域词典

语法最简单的微博通用爬虫weibo_crawler
hiResearch 定义自己的科研首页
SciencePlots | 科研样式绘图库
plydata库 | 数据操作管道操作符>>
plotnine: Python版的ggplot2作图库
Wow~70G上市公司定期报告数据集

漂亮~pandas可以无缝衔接Bokeh  
YelpDaset: 酒店管理类数据集10+G
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值