在matplotlib中自定义图例的间隔

时间:2017-06-13 18:06:32

标签: python-2.7 pandas matplotlib legend

我正在使用histogram2D,contourf和matplotlib从csv文件中绘制密度图。 请看看我的结果: enter image description here

所以,我的主要要求是定制我的图例的间隔,我需要只有5个间隔,步长为0.8,例如,当涉及间隔> 2.5我希望它只是在相同颜色的间隔上并用"标记。 2.5及以上。 这是我用来自定义我的图例的代码:

cmap = plt.cm.get_cmap('Paired', 8)
cs = m.contourf(xi, yi, g, cmap = cmap)
cbar = plt.colorbar(cs, orientation='horizontal')
cbar.set_label('la densite des impacts foudre',size=18)

# Set borders in the interval [0, 1]
bound = np.linspace(0, 1, 9)
# Preparing borders for the legend
bound_prep = np.round(bound * 7, 2)
# Creating 8 Patch instances
plt.legend([mpatches.Patch(color=cmap(b)) for b in bound[:-1]],
       ['{} - {}'.format(bound_prep[i], bound_prep[i+1] - 0.01) for i in range(8)], bbox_to_anchor=(1.05, 1), loc=2)
plt.gcf().set_size_inches(15,15)
plt.show() 

所以基本上我需要一个类似于这个的传奇:

enter image description here

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我不确定,如果我现在理解正确的话。对我来说,只使用图中完全相同数量的水平才有意义,如图例所示。

当然,您可以通过levels参数contourf手动选择要使用的级别。

import matplotlib.pyplot as plt
import numpy as np

x= np.linspace(-3,3)
X,Y = np.meshgrid(x,x)
Z = np.exp(-(X**2+Y**2))

levels = [0,.1,.2,.3,.4,.5,1]
cmap=plt.cm.get_cmap("Paired")
colors=list(map(cmap, range(len(levels))))


fig,ax=plt.subplots()
cf = ax.contourf(X,Y,Z, levels=levels, colors=colors )
fig.colorbar(cf)

handles = [plt.Rectangle((0,0),1,1, color=c) for c in colors]
labels = [u"de {} à {}".format(levels[i], levels[i+1]) for i in range(len(levels)-1)]
labels[-1] = "plus de {}".format(levels[-2])
ax.legend(handles, labels)

plt.show()

enter image description here