python数据整理代码_熬夜整理的资料:分享Python数据可视化图表代码和案例给大家...
前言
本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。
闲话不多说,直接上干货
1华夫饼图
waffle可以使用该pywaffle软件包创建该图表,并用于显示较大人群中各组的组成。
#! pip install pywaffle#Reference: https://stackoverflow.com/questions/41400136/how-to-do-waffle-charts-in-python-square-piechart
from pywaffle importWaffle#Import
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('class').size().reset_index(name='counts')
n_categories=df.shape[0]
colors= [plt.cm.inferno_r(i/float(n_categories)) for i inrange(n_categories)]#Draw Plot and Decorate
fig =plt.figure(
FigureClass=Waffle,
plots={'111': {'values': df['counts'],'labels': ["{0} ({1})".format(n[0], n[1]) for n in df[['class', 'counts']].itertuples()],'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12},'title': {'label': '# Vehicles by Class', 'loc': 'center', 'fontsize':18}
},
},
rows=7,
colors=colors,
figsize=(16, 9)
)
#! pip install pywaffle
from pywaffle importWaffle#Import#df_raw = pd.read_csv("data/mpg_ggplot2.csv")
#Prepare Data#By Class Data
df_class = df_raw.groupby('class').size().reset_index(name='counts_class')
n_categories=df_class.shape[0]
colors_class= [plt.cm.Set3(i/float(n_categories)) for i inrange(n_categories)]#By Cylinders Data
df_cyl = df_raw.groupby('cyl').size().reset_index(name='counts_cyl')
n_categories=df_cyl.shape[0]
colors_cyl= [plt.cm.Spectral(i/float(n_categories)) for i inrange(n_categories)]#By Make Data
df_make = df_raw.groupby('manufacturer').size().reset_index(name='counts_make')
n_categories=df_make.shape[0]
colors_make= [plt.cm.tab20b(i/float(n_categories)) for i inrange(n_categories)]#Draw Plot and Decorate
fig =plt.figure(
FigureClass=Waffle,
plots={'311': {'values': df_class['counts_class'],'labels': ["{1}".format(n[0], n[1]) for n in df_class[['class', 'counts_class']].itertuples()],'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Class'},'title': {'label': '# Vehicles by Class', 'loc': 'center', 'fontsize':18},'colors': colors_class
},'312': {'values': df_cyl['counts_cyl'],'labels': ["{1}".format(n[0], n[1]) for n in df_cyl[['cyl', 'counts_cyl']].itertuples()],'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Cyl'},'title': {'label': '# Vehicles by Cyl', 'loc': 'center', 'fontsize':18},'colors': colors_cyl
},'313': {'values': df_make['counts_make'],'labels': ["{1}".format(n[0], n[1]) for n in df_make[['manufacturer', 'counts_make']].itertuples()],'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Manufacturer'},'title': {'label': '# Vehicles by Make', 'loc': 'center', 'fontsize':18},'colors': colors_make
}
},
rows=9,
figsize=(16, 14)
)
2 饼图
饼图是显示组组成的经典方法。但是,如今一般不建议使用它,因为馅饼部分的面积有时可能会引起误解。因此,如果要使用饼图,强烈建议明确写下饼图各部分的百分比或数字。
#Import
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('class').size()#Make the plot with pandas
df.plot(kind='pie', subplots=True, figsize=(8, 8), dpi= 80)
plt.title("Pie Chart of Vehicle Class - Bad")
plt.ylabel("")
plt.show()
#Import
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('class').size().reset_index(name='counts')#Draw Plot
fig, ax = plt.subplots(figsize=(12, 7), subplot_kw=dict(aspect="equal"), dpi= 80)
data= df['counts']
categories= df['class']
explode= [0,0,0,0,0,0.1,0]deffunc(pct, allvals):
absolute= int(pct/100.*np.sum(allvals))return "{:.1f}% ({:d} )".format(pct, absolute)
wedges, texts, autotexts=ax.pie(data,
autopct=lambdapct: func(pct, data),
textprops=dict(color="w"),
colors=plt.cm.Dark2.colors,
startangle=140,
explode=explode)#Decoration
ax.legend(wedges, categories, title="Vehicle Class", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))
plt.setp(autotexts, size=10, weight=700)
ax.set_title("Class of Vehicles: Pie Chart")
plt.show()
3 树状图
树形图类似于饼形图,并且可以更好地完成工作,而不会误导每个组的贡献。
#pip install squarify
importsquarify#Import Data
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('class').size().reset_index(name='counts')
labels= df.apply(lambda x: str(x[0]) + "n (" + str(x[1]) + ")", axis=1)
sizes= df['counts'].values.tolist()
colors= [plt.cm.Spectral(i/float(len(labels))) for i inrange(len(labels))]#Draw Plot
plt.figure(figsize=(12,8), dpi= 80)
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=.8)#Decorate
plt.title('Treemap of Vechile Class')
plt.axis('off')
plt.show()
4 条形图
条形图是一种基于计数或任何给定指标可视化项目的经典方法。在下面的图表中,我为每个项目使用了不同的颜色,但是您通常可能希望为所有项目选择一种颜色,除非您按组对它们进行着色。颜色名称存储在all_colors下面的代码中。您可以通过在中设置color参数来更改条形的颜色。
importrandom#Import Data
df_raw = pd.read_csv("data/mpg_ggplot2.csv")#Prepare Data
df = df_raw.groupby('manufacturer').size().reset_index(name='counts')
n= df['manufacturer'].unique().__len__()+1all_colors=list(plt.cm.colors.cnames.keys())
random.seed(100)
c= random.choices(all_colors, k=n)#Plot Bars
plt.figure(figsize=(16,10), dpi= 80)
plt.bar(df['manufacturer'], df['counts'], color=c, width=.5)for i, val in enumerate(df['counts'].values):
plt.text(i, val, float(val), horizontalalignment='center', verticalalignment='bottom', fontdict={'fontweight':500, 'size':12})#Decoration
plt.gca().set_xticklabels(df['manufacturer'], rotation=60, horizontalalignment= 'right')
plt.title("Number of Vehicles by Manaufacturers", fontsize=22)
plt.ylabel('# Vehicles')
plt.ylim(0,45)
plt.show()
不管你是零基础还是有基础都可以获取到自己相对应的学习礼包!包括Python软件工具和2020最新入门到实战教程。加群695185429即可免费获取。
内容来源于网络如有侵权请私信删除
python数据整理代码_熬夜整理的资料:分享Python数据可视化图表代码和案例给大家...相关推荐
- 数据统计 测试方法_统计测试:了解如何为数据选择最佳测试!
数据统计 测试方法 This post is not meant for seasoned statisticians. This is geared towards data scientists ...
- 深度学习数据集中数据差异大_使用差异隐私来利用大数据并保留隐私
深度学习数据集中数据差异大 The modern world runs on "big data," the massive data sets used by governmen ...
- 资料分享 | python机器学习教程分享来袭
小天从大学开始,便开启资料收集功能.近几年以AlphaGo为契机,人工智能进入新的发展阶段,再加上日常的深入研究,小天收集整理了丰富的机器学习资料,内容涵盖"机器学习视频",&qu ...
- gridcontrol选中多行数据进行复制_终于整理全了,数据核对的6钟方法,掌握它们数据核对你就是大神...
hello,大家好,数据核对是我们早工作中绕不开的话题,费时费力不说,正确率还难以保证,有时候同事几分钟就搞定,自己却做了两三个小时.表格的设计千差万别,只掌握一种数据核对的方法是不能满足工作需求的, ...
- python不会怎么办_怕你还不会Python函数,我特意为你整理了一篇博客
什么是函数 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.你已经知道Python提供了许多内建函数,比如print().但你也可以自己 ...
- numpy是python标准库吗_吐血 整理!140种Python标准库、第三方库和外部工具都有了...
Python数据工具箱涵盖从数据源到数据可视化的完整流程中涉及到的常用库.函数和外部工具.其中既有Python内置函数和标准库,又有第三方库和工具. 这些库可用于文件读写.网络抓取和解析.数据连接.数 ...
- python ssd目标检测_目标检测算法之SSD的数据增强策略
前言 这篇文章是对前面<目标检测算法之SSD代码解析>,推文地址如下:点这里的补充.主要介绍SSD的数据增强策略,把这篇文章和代码解析的文章放在一起学最好不过啦.本节解析的仍然是上篇SSD ...
- 朴素贝叶斯python代码_朴素贝叶斯模型及python实现
1 朴素贝叶斯模型 朴素贝叶斯法是基于贝叶斯定理.特征条件独立假设的分类方法.在预测时,对输入x,找出对应后验概率最大的 y 作为预测. NB模型: 输入: 先验概率分布:P(Y=ck),k=1,2, ...
- tushare数据存入mysql代码_下载股票的历史日交易数据并存入数据库——基于tushare...
tushare是一个非常神奇的Python模块包,基于新浪的API,可提供并不限于股票的历史数据. 数据库选用的是sqlite3,单文件,轻量化,不需要配置. 以下是完整代码,且使用的是多线程的方式. ...
最新文章
- linux入门教程(二)
- mysql中的时间函数---运维常用
- 15个相当不错的jQuery技巧
- VoltDB公布4.0版本号,大步提高内存实时分析速度,进军操作数据库市场
- 面向对象之: 类空间问题及类之间的关系
- 预测未来的环境,提前做出改变
- 简书android 输入法设置,Android输入法弹出流程
- 拓端tecdat:Python金融时间序列模型ARIMA 和GARCH 在股票市场预测应用
- 深入解读Linux进程调度系列(7)——调度与CPU隔离
- JAVA Eclipse如何设置点击按钮切换图片
- 修改后的取得汉字首字母的lazarus函数,可以自己增加疑难汉字,这个应该比较理想了
- 2018杭州·云栖大会:一文直击地表最强黑科技
- Office2013办公软件简体中文专业增强版
- 快速实现NBIOT UDP通信
- Cisco设备telnet登录设置
- Logo常用的12种颜色
- 协调世界时间 UTC
- 彻底弄懂@Controller 、@Service、@Component
- Python实现壁纸批量下载
- 零 距 离 感 悟 金 山
热门文章
- 转 容器生态系统 (续) - 每天5分钟玩转容器技术(3)
- VirtualBox中安装CentOS(新手教程)
- 第二次作业(个人项目实践)
- listalias - 列出用户和系统别名
- 0.11内核rd_load@ramdisk.c中memcpy函数好像有bug
- 【bzoj2724】[Violet 6]蒲公英 分块+STL-vector
- 想拿高新就必须知道的知识
- 最大公共子串提取“模式”
- 【NOI2016】优秀的拆分(后缀数组)
- [Codeforces 555E]Case of Computer Network(Tarjan求边-双连通分量+树上差分)