轻松地
easyplotl的Python项目详细描述
轻松地
这是关于如何用Plotly.py绘图的正在进行的研究, 尤其是绘制层次数据,可以变得更容易。在
查看下面命令的输出-表格和绘图-
在这个笔记本的HTML export中。
甚至可以将此README.md
作为笔记本打开,并在上面以交互方式运行它
Binder!在
安装
使用安装easyplotly
python包
pip install easyplotly
样本数据
我们的样本数据是每个国家和地区的人口和预期寿命:
^{pr2}$太阳暴流图
importplotly.graph_objectsasgoimportplotly.ioaspioimporteasyplotlyaseppio.renderers.default='notebook_connected'layout=go.Layout(title='World Population and Life Expectancy<br>Data from the World Bank',height=800)
我们的Sunburst
函数接受多种类型的输入:pandas系列、字典和此类对象的列表。
如果需要,可以重新定义labels
,或添加其他参数,如text
-使用带索引的序列
与values
的相同,或对任何元组(level0, level1, ... leveln)
的函数
关联相应的标签或值。在
sunburst=ep.Sunburst(pop_and_exp.population,text=pop_and_exp.life_expectancy)go.Figure(sunburst,layout)
树状图
Treemap
函数的工作原理与Sunburst
函数类似:
treemap=ep.Treemap(pop_and_exp.population,text=pop_and_exp.life_expectancy)go.Figure(treemap,layout)
就像Sunburst
函数一样,它也接受原始函数支持的所有参数
go.Sunburst
对象。甚至欢迎您使用
magic underscore notation,
下面我们用marker_colors
设置marker.colors
:
importnumpyasnpdefaverage(values,weights):"""Same as np.average, but remove nans"""total_obs=0.total_weight=0.ifisinstance(values,np.float):values=[values]weights=[weights]forx,winzip(values,weights):xw=x*wifnp.isnan(xw):continuetotal_obs+=xwtotal_weight+=wreturntotal_obs/total_weightiftotal_weight!=0elsenp.NaNdeflife_expectancy(item):"""Life expectancy associated to a tuple like (), ('Europe & Central Asia') or ('East Asia & Pacific', 'China')"""sub=pop_and_exp.loc[item]ifitemelsepop_and_expreturnaverage(sub.life_expectancy,weights=sub.population)deftext(item):"""Return the text associated to a tuple like (), ('Europe & Central Asia') or ('East Asia & Pacific', 'China')"""life_exp=life_expectancy(item)iflife_exp>0:pop=pop_and_exp.population.loc[item].sum()ifitemelsepop_and_exp.population.sum()return'Population: {:,}<br>Life expectancy: {:.2f}'.format(int(pop),life_exp)treemap=ep.Treemap(pop_and_exp.population,hoverinfo='label+text',text=text,root_label='World',# magic underscore notationmarker_colors=life_expectancy,marker_colorscale='RdBu')go.Figure(treemap,layout)
桑基地块
从dict或具有源/目标多重索引的序列中绘制链接:
links={('A','B'):3,('B','C'):1,('B','D'):2,('C','A'):1,('D','A'):1,('A','D'):1}go.Figure(ep.Sankey(links))
从数据帧打印链接(源作为索引,目标作为列):
importpandasaspd
links=pd.DataFrame(1,index=['Source A','Source B'],columns=['Target'])go.Figure(ep.Sankey(links))
我们用一个情节来总结例子,其中的链接是熊猫系列的列表:
region_income=wb.get_countries().query("region != 'Aggregates'").copy()region_income['population']=wb.get_series('SP.POP.TOTL',mrv=1,id_or_value='id',simplify_index=True)income_lending=region_income.copy()region_income.set_index(['region','incomeLevel'],inplace=True)income_lending.set_index(['incomeLevel','lendingType'],inplace=True)layout=go.Layout(title='Regions income and lending type<br>Data from the World Bank')sankey=ep.Sankey(link_value=[region_income['population'],income_lending['population']],link_label=[region_income['name'],income_lending['name']])go.Figure(sankey,layout)
- 项目
标签: