代码详解:如何用Python快速制作美观、炫酷且有深度的图表
![](/assets/blank.gif)
![](/assets/blank.gif)
![](/assets/blank.gif)
![](/assets/blank.gif)
1. 我使用Python进行绘图的经历
![](/assets/blank.gif)
![](/assets/blank.gif)
2. 分布的重要性
![](/assets/blank.gif)
![](/assets/blank.gif)
3. 加载数据和包导入
![](/assets/blank.gif)
# Loadthe data
data = pd.read_csv('https://raw.githubusercontent.com/FBosler/AdvancedPlotting/master/combined_set.csv')#this assigns labels per year
data['Mean Log GDP per capita'] =data.groupby('Year')['Log GDP per capita'].transform(
pd.qcut,
q=5,
labels=(['Lowest','Low','Medium','High','Highest'])
)
import plotly
import pandas as pd
import numpy as np
import seaborn as sns
import plotly.express as pximport matplotlib%matplotlib inlineassertmatplotlib.__version__ == "3.1.0","""
Please install matplotlib version 3.1.0 by running:
1) !pip uninstall matplotlib
2) !pip install matplotlib==3.1.0
"""
![](/assets/blank.gif)
4. 迅速:使用Pandas进行基本绘图
![](/assets/blank.gif)
np.exp(data[data['Year']==2018]['LogGDP per capita']).plot(
kind='hist'
)
![](/assets/blank.gif)
data[
data['Year'] == 2018
].set_index('Country name')['Life Ladder'].nlargest(15).plot(
kind='bar',
figsize=(12,8)
)
![](/assets/blank.gif)
np.exp(data[
data['Year'] == 2018
].groupby('Continent')['Log GDP per capita']\
.mean()).sort_values().plot(
kind='barh',
figsize=(12,8)
)
![](/assets/blank.gif)
data['Life Ladder'].plot(
kind='box',
figsize=(12,8)
)
![](/assets/blank.gif)
data[['Healthy life expectancyat birth','Gapminder Life Expectancy']].plot(
kind='scatter',
x='Healthy life expectancy at birth',
y='Gapminder Life Expectancy',
figsize=(12,8)
)
![](/assets/blank.gif)
data[data['Year'] == 2018].plot( kind='hexbin', x='Healthy life expectancy at birth', y='Generosity', C='Life Ladder', gridsize=20, figsize=(12,8), cmap="Blues", # defaults togreenish sharex=False # required to get rid ofa bug)
![](/assets/blank.gif)
data[data['Year'] == 2018].groupby(
['Continent']
)['Gapminder Population'].sum().plot(
kind='pie',
figsize=(12,8),
cmap="Blues_r", # defaultsto orangish
)
![](/assets/blank.gif)
data.groupby(
['Year','Continent']
)['Gapminder Population'].sum().unstack().plot(
kind='area',
figsize=(12,8),
cmap="Blues", # defaults toorangish
)
![](/assets/blank.gif)
data[ data['Country name'] == 'Germany'].set_index('Year')['Life Ladder'].plot( kind='line', figsize=(12,8))
![](/assets/blank.gif)
![](/assets/blank.gif)
5. 美观:使用Seaborn进行高级绘图
![](/assets/blank.gif)
sns.reset_defaults()
sns.set(
rc={'figure.figsize':(7,5)},
style="white" # nicerlayout
)
![](/assets/blank.gif)
sns.jointplot(
x='Log GDP per capita',
y='Life Ladder',
data=data,
kind='scatter' # or 'kde' or 'hex'
)
![](/assets/blank.gif)
sns.scatterplot(
x='Log GDP per capita',
y='Life Ladder',
data=data[data['Year'] == 2018],
hue='Continent',
size='Gapminder Population'
)# both, hue and size are optional
sns.despine() # prettier layout
![](/assets/blank.gif)
sns.set( rc={'figure.figsize':(18,6)}, style="white")sns.violinplot( x='Continent', y='Life Ladder', hue='Mean Log GDP per capita', data=data)sns.despine()
![](/assets/blank.gif)
sns.set(
style="white",
palette="muted",
color_codes=True
)sns.pairplot(
data[data.Year == 2018][[
'Life Ladder','Log GDP percapita',
'Social support','Healthy lifeexpectancy at birth',
'Freedom to make lifechoices','Generosity',
'Perceptions of corruption','Positive affect',
'Negative affect','Confidence innational government',
'Mean Log GDP per capita'
]].dropna(),
hue='Mean Log GDP per capita'
)
![](/assets/blank.gif)
g = sns.FacetGrid(
data.groupby(['Mean Log GDP percapita','Year','Continent'])['Life Ladder'].mean().reset_index(),
row='Mean Log GDP per capita',
col='Continent',
margin_titles=True
)
g = (g.map(plt.plot, 'Year','Life Ladder'))
![](/assets/blank.gif)
g = sns.FacetGrid(data,col="Continent", col_wrap=3,height=4)
g = (g.map(plt.hist, "Life Ladder",bins=np.arange(2,9,0.5)))
![](/assets/blank.gif)
![](/assets/blank.gif)
defvertical_mean_line(x, **kwargs):
plt.axvline(x.mean(), linestyle="--",
color= kwargs.get("color", "r"))
txkw =dict(size=15, color= kwargs.get("color", "r"))
label_x_pos_adjustment =0.08# this needs customization based on your data
label_y_pos_adjustment =5# this needs customization based on your data
if x.mean() <6: # this needs customization based on your data
tx ="mean: {:.2f}\n(std: {:.2f})".format(x.mean(),x.std())
plt.text(x.mean() + label_x_pos_adjustment, label_y_pos_adjustment, tx, **txkw)
else:
tx ="mean: {:.2f}\n (std: {:.2f})".format(x.mean(),x.std())
plt.text(x.mean() -1.4, label_y_pos_adjustment, tx, **txkw)
_ = data.groupby(['Continent','Year'])['Life Ladder'].mean().reset_index()
g = sns.FacetGrid(_, col="Continent", height=4, aspect=0.9, col_wrap=3, margin_titles=True)
g.map(sns.kdeplot, "Life Ladder", shade=True, color='royalblue')
g.map(vertical_mean_line, "Life Ladder")
![](/assets/blank.gif)
heatmap_facetgrid.py
defdraw_heatmap(data,inner_row, inner_col, outer_row, outer_col, values, vmin,vmax):
sns.set(font_scale=1)
fg = sns.FacetGrid(
data,
row=outer_row,
col=outer_col,
margin_titles=True
)
position = left, bottom, width, height =1.4, .2, .1, .6
cbar_ax = fg.fig.add_axes(position)
fg.map_dataframe(
draw_heatmap_facet,
x_col=inner_col,
y_col=inner_row,
values=values,
cbar_ax=cbar_ax,
vmin=vmin,
vmax=vmax
)
fg.fig.subplots_adjust(right=1.3)
plt.show()
defdraw_heatmap_facet(*args, **kwargs):
data = kwargs.pop('data')
x_col = kwargs.pop('x_col')
y_col = kwargs.pop('y_col')
values = kwargs.pop('values')
d = data.pivot(index=y_col, columns=x_col, values=values)
annot =round(d,4).values
cmap = sns.color_palette("Blues",30) + sns.color_palette("Blues",30)[0::2]
#cmap = sns.color_palette("Blues",30)
sns.heatmap(
d,
**kwargs,
annot=annot,
center=0,
cmap=cmap,
linewidth=.5
)
# Data preparation
_ = data.copy()
_['Year'] = pd.cut(_['Year'],bins=[2006,2008,2012,2018])
_['GDP per Capita'] = _.groupby(['Continent','Year'])['Log GDP per capita'].transform(
pd.qcut,
q=3,
labels=(['Low','Medium','High'])
).fillna('Low')
_['Corruption'] = _.groupby(['Continent','GDP per Capita'])['Perceptions of corruption'].transform(
pd.qcut,
q=3,
labels=(['Low','Medium','High'])
)
_ = _[_['Continent'] !='Oceania'].groupby(['Year','Continent','GDP per Capita','Corruption'])['Life Ladder'].mean().reset_index()
_['Life Ladder'] = _['Life Ladder'].fillna(-10)
draw_heatmap(
data=_,
outer_row='Corruption',
outer_col='GDP per Capita',
inner_row='Year',
inner_col='Continent',
values='Life Ladder',
vmin=3,
vmax=8,
)
![](/assets/blank.gif)
6. 精彩:用plotly创造精彩的互动情节
![](/assets/blank.gif)
fig = x.<PLOTTYPE>(PARAMS)然后是 fig.show() ,像这样:
fig = px.scatter(
data_frame=data[data['Year'] ==2018],
x="Log GDP per capita",
y="Life Ladder",
size="GapminderPopulation",
color="Continent",
hover_name="Country name",
size_max=60
)
fig.show()
![](/assets/blank.gif)
fig = px.scatter(
data=data,
x="Log GDP per capita",
y="Life Ladder",
animation_frame="Year",
animation_group="Countryname",
size="GapminderPopulation",
color="Continent",
hover_name="Country name",
facet_col="Continent",
size_max=45,
category_orders={'Year':list(range(2007,2019))}
)fig.show()
![](/assets/blank.gif)
def q_bin_in_3(col):
return pd.qcut(
col,
q=3,
labels=['Low','Medium','High']
)_ = data.copy()
_['Social support'] = _.groupby('Year')['Socialsupport'].transform(q_bin_in_3)_['Life Expectancy'] =_.groupby('Year')['Healthy life expectancy atbirth'].transform(q_bin_in_3)_['Generosity'] =_.groupby('Year')['Generosity'].transform(q_bin_in_3)_['Perceptions ofcorruption'] = _.groupby('Year')['Perceptions ofcorruption'].transform(q_bin_in_3)_ = _.groupby(['Social support','LifeExpectancy','Generosity','Perceptions of corruption'])['LifeLadder'].mean().reset_index()fig = px.parallel_categories(_, color="LifeLadder", color_continuous_scale=px.colors.sequential.Inferno)
fig.show()
![](/assets/blank.gif)
fig = px.bar(
data,
x="Continent",
y="Gapminder Population",
color="Mean Log GDP percapita",
barmode="stack",
facet_col="Year",
category_orders={"Year":range(2007,2019)},
hover_name='Country name',
hover_data=[
"Mean Log GDP percapita",
"Gapminder Population",
"Life Ladder"
]
)
fig.show()
![](/assets/blank.gif)
fig = px.choropleth( data, locations="ISO3", color="Life Ladder", hover_name="Country name", animation_frame="Year")fig.show()
![](/assets/blank.gif)
![](/assets/blank.gif)
结束语
![](/assets/blank.gif)
![](/assets/blank.gif)
![](/assets/blank.gif)
![](/assets/blank.gif)
![](/assets/blank.gif)
![](/assets/blank.gif)
![](/assets/blank.gif)
代码详解:如何用Python快速制作美观、炫酷且有深度的图表相关推荐
- python批量下载文件只有1kb_详解如何用python实现一个简单下载器的服务端和客户端...
话不多说,先看代码: 客户端: import socket def main(): #creat: download_client=socket.socket(socket.AF_INET,socke ...
- 万字长文详解如何用Python玩转OpenGL | CSDN 博文精选
作者 | 天元浪子 来源 | CSDN博文精选 [编者按]OpenGL(开放式图形库),用于渲染 2D.3D 矢量图形的跨语言.跨平台的应用程序编程接口,C.C++.Python.Java等语言都能支 ...
- ucos 消息队列代码详解_用python实现 多进程队的列数据处理详解,零基础记得都收藏哦
今天就为大家分享一篇python 多进程队列数据处理详解,具有很好的参考价值,希望对大家有所帮助.喜欢的话记得点赞转发关注不迷路哦!!! 总之了写到多进程队列数据处理问题,也就不多废话了,直接来上代码 ...
- 万字长文详解如何用 Python 玩转 OpenGL | CSDN 博文精选
作者 | 天元浪子 责编 | 伍杏玲 出品 | CSDN 博客 [CSDN 编者按]OpenGL(开放式图形库),用于渲染 2D.3D 矢量图形的跨语言.跨平台的应用程序编程接口,C.C++.Pyth ...
- 代码详解:用Python给你喜欢的音乐分个类吧
点击上方 "程序员小乐"关注, 星标或置顶一起成长 每天凌晨00点00分, 第一时间与你相约 每日英文 Everyone to hello, not an obligation. ...
- 代码详解 | 用Pytorch训练快速神经网络的9个技巧
点击上方"视学算法",选择加"星标"或"置顶" 重磅干货,第一时间送达 作者丨William Falcon 来源丨稀牛Xiniu 编辑丨极市 ...
- python提取excel数据-代码详解:使用Python从不同表格中提取数据
常用的表格数据存储文件格式--CSV,Microsoft Excel,Google Excel . Python通常称为粘合语言.这个名称归因于人们逐渐开发出的大量接口库和特征,也得益于广泛的使用和良 ...
- python处理表格数据教程_代码详解:使用Python从不同表格中提取数据
常用的表格数据存储文件格式--CSV,Microsoft Excel,Google Excel . Python通常称为粘合语言.这个名称归因于人们逐渐开发出的大量接口库和特征,也得益于广泛的使用和良 ...
- 如何用python创建一个下载网站-详解如何用python实现一个简单下载器的服务端和客户端...
话不多说,先看代码: 客户端: import socket def main(): #creat: download_client=socket.socket(socket.AF_INET,socke ...
最新文章
- SSM始用 @Autowired(required = false)的一个坑
- 简单,为什么要复杂和妥协?
- java 抽象接口类,Java接口(interface)和Java抽象类(abstract class)的区别(详诉版)
- RC隔离级别下的GAP间隙锁
- git ignore 某行
- 软件开发管理与质量控制
- 二分插入排序(折半插入排序)--排序算法(六)
- ABIs [armeabi] are not supported for platform. Supported ABIs are [arm64-v8a, armeabi......
- 单链表学生管理系统(0723-林雪阵)
- chrome应用程序无法正常启动0x0000005
- 第11章 UART串口通信 练习题
- starUML for MAC 破解方法
- 【转】《与MySQL的零距离接触》第四章:操作数据表中的记录 (4-2:MySQL 插入记录INSERT)
- 【Python网络编程和并发-多线程共享数据混乱引出同步锁】
- Spring AOP实现原理,从代理说起
- 【揭秘恒大老总许家印】迄今为止最深度、全面的
- 洛谷P1460 健康的荷斯坦奶牛
- 鸿蒙车载智慧屏评测,【首款搭载鸿蒙操作系统荣耀智慧屏评测 颜值爆表 亮点颇多】PjTime.COM 评测试用 华为...
- Windows 下 vc++运行库安装,Microsoft Visual C++ Build Tools官方工具
- hp服务器安装ghost系统安装,惠普电脑/HP笔记本无法安装GHOST系统的解决方法