2010-07-19 96 views
12

我感兴趣的画treemap树形图图表在Python

treemap example

是什么力量让一个在Python的最简单的方法?鉴于正确的输入数据,是否有图书馆可以制作这样的图形?

+1

7年过去了,仍然没有像样的python软件包能够绘制简单的treemap。下面列出的答案仍然是最先进的,但非常无益。使用R或js它是两行代码的问题,但为什么在Python中如此复杂?我不明白。 – MERose 2017-02-22 12:49:35

回答

3

这些可用于:

我注意到,有在PyPI中也树形图库。我没有试过那个。

+0

matlab方法实际上是一个SciPy食谱,可在http://scipy-cookbook.readthedocs.io/items/Matplotlib_TreeMap.html – MERose 2017-02-22 12:17:26

2

这里有几个选项:

+0

记录不当。不能推荐他们。 – MERose 2017-02-22 12:27:20

1

您可以使用Pygal库,这是如此简单

http://pygal.org/en/stable/documentation/types/treemap.html

另一种方法是你可以使用squarify库,这里就是我使用了代码

import matplotlib 
import matplotlib.pyplot as plt 
import pandas as pd 
import squarify 

# qualtities plotted 
# squarre area is the town surface area (superf) 
# color scale is the town population in 2011 (p11_pop) 

# read data from csv file 
# data from CAPP opendata http://opendata.agglo-pau.fr/index.php/fiche?idQ=27 
df = pd.read_excel("Customer Success New.xlsx") 
df = df.set_index("location_id") 
df = df[["user_id", "company_id"]] 
df2 = df.sort_values(by="user_id", ascending=False) 

# treemap parameters 
x = 0. 
y = 0. 
width = 100. 
height = 100. 
cmap = matplotlib.cm.viridis 

# color scale on the population 
# min and max values without Pau 
mini, maxi = df2.company_id.min(), df2.company_id.max() 
norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi) 
colors = [cmap(norm(value)) for value in df2.company_id] 
colors[1] = "#FBFCFE" 

# labels for squares 
#labels = ["hab" % (label) for label in zip(df2.index, df2.user_id), df2.company_id)] 
#labels[11] = "MAZERES" % (df2["user_id"]["MAZERES-LEZONS"], df2["company_id"]["MAZERES-LEZONS"]) 

# make plot 
fig = plt.figure(figsize=(12, 10)) 
fig.suptitle("Population et superficie des communes de la CAPP", fontsize=20) 
ax = fig.add_subplot(111, aspect="equal") 
ax = squarify.plot(df2.superf, color=colors, label=labels, ax=ax, alpha=.7) 
ax.set_xticks([]) 
ax.set_yticks([]) 
ax.set_title("L'aire de chaque carré est proportionnelle à la superficie de la commune\n", fontsize=14) 

# color bar 
# create dummy invisible image with a color map 
img = plt.imshow([df2.p11_pop], cmap=cmap) 
img.set_visible(False) 
fig.colorbar(img, orientation="vertical", shrink=.96) 

fig.text(.76, .9, "Population", fontsize=14) 
fig.text(.5, 0.1, 
     "Superficie totale %d km2, Population de la CAPP : %d hab" % (df2.superf.sum(), df2.p11_pop.sum()), 
     fontsize=14, 
     ha="center") 
fig.text(.5, 0.07, 
     "Source : http://opendata.agglo-pau.fr/", 
     fontsize=14, 
     ha="center") 

plt.show() 
+1

尽管这个链接可能回答这个问题,但最好在这里包含答案的基本部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/评论/低质量帖子/ 17434830) – Oz123 2017-09-25 07:26:23

+0

好吧,感谢您的反馈,我会更新我的答案 – 2017-09-25 07:44:34

+0

@NabihIbrahimBawazir看起来好多了,谢谢你更新你的答案! – g00glen00b 2017-09-25 08:13:03