如何使用matplotlib和python制作表格图例

时间:2017-06-15 12:08:09

标签: python-2.7 matplotlib legend

我正在使用shapefile在python中绘制一个等值区域地图,我想自定义绘图的图例,我正在使用下面的代码:

import pandas as pd
import pysal as ps
import geopandas as gp
import numpy as np
import matplotlib.pyplot as plt

pth = 'outcom.shp'
tracts = gp.GeoDataFrame.from_file(pth)
ax = plot_dataframe(tracts, column='Density', scheme='QUANTILES', k=4, colormap=plt.cm.Blues, legend=True)
plt.show()

此外,我正在使用我在http://nbviewer.ipython.org/gist/jorisvandenbossche/d4e6efedfa1e4e91ab65找到的一个小补丁来显示图例。

这是我的结果: enter image description here 但是,我需要类似的东西:

enter image description here

现在我的问题是,我如何才能拥有自定义传奇

1 个答案:

答案 0 :(得分:1)

您可以使用plt.table作为图例。

enter image description here

import matplotlib.pyplot as plt
import numpy as np

valeur = np.array([.1,.45,.7])
text=[["Faible","Ng<1,5" ],["Moyenne","1,5<Ng<2,5"],[u"Elevée", "Ng>2,5"]]
colLabels = ["Exposition", u"Densité"]


tab=plt.table(cellText=text, colLabels=colLabels, 
                    colWidths = [0.2,0.2], loc='lower right', 
                    cellColours=plt.cm.hot_r(np.c_[valeur,valeur]))

plt.show()

为了将此表链接到contourf图,您可以执行以下操作:

from matplotlib import pyplot as plt
import numpy as np

a = np.sort(np.random.rand(100)).reshape(10,10)*4

levels = np.array([0,1.5,2.5,4])
sm = plt.contourf(a, levels = levels, cmap=plt.cm.hot_r )


text=[["Faible","Ng<1,5" ],["Moyenne","1,5<Ng<2,5"],[u"Elevée", "Ng>2,5"]]
colLabels = ["Exposition", u"Densité"]

col = levels[:-1] + np.diff(levels)/2.
cellcol = sm.cmap(sm.norm(np.c_[col,col]))

tax = plt.gcf().add_axes([0,0,1,1])
tab=tax.table(cellText=text, colLabels=colLabels, 
                    colWidths = [0.2,0.2], loc='lower left', 
                    cellColours=cellcol )

tax.axis("off")
plt.show()

enter image description here