Python 2.7 在matplotlib中自定义图例的间隔

Python 2.7 在matplotlib中自定义图例的间隔,python-2.7,pandas,matplotlib,legend,Python 2.7,Pandas,Matplotlib,Legend,我正在使用histogram2D、contourf和matplotlib从csv文件绘制密度图。 请看一下我的结果: 因此,我的主要要求是自定义图例的间隔,例如,我只需要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

我正在使用histogram2D、contourf和matplotlib从csv文件绘制密度图。 请看一下我的结果:

因此,我的主要要求是自定义图例的间隔,例如,我只需要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() 
所以基本上我需要一个类似于这个的传说:


有什么想法吗?

如果我现在理解正确,我不确定。对我来说,在情节中使用与图例所示完全相同的层数才有意义

当然,您可以通过
tourtf
levels
参数手动选择要使用的标高

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()

我在理解你想要的结果时遇到问题。你说你想有5个间隔,但代码中已经有8个级别。而且如果间隔为0.8,你只能得到3个和第八个间隔,最多2.5个。间隔的颜色与等高线图的颜色有什么关系?显然你真的理解我的d预期的结果,所以是的,我有8个间隔,但我需要管理,以保持只有6或5个间隔,一个步骤低于0.8,当然,间隔高达2.5应该在一个总结间隔称为2.5和以上,并具有独特的颜色。是的,这就是我要找的,非常感谢你的帮助!