无法添加matplotlib colorbar ticks

时间:2017-03-04 23:34:35

标签: python-3.x matplotlib matplotlib-basemap colorbar

我正在尝试将滴答和标签添加到颜色栏,但它似乎没有出现在输出中。我尝试了两种方法(如下面的代码所示)。第二个appraoch要做,如Stack Overflow上的另一个问题所示:How to add Matplotlib Colorbar Ticks

我必须在这里忽略一些非常简单的东西,因为我是Matplotlib和Python的初学者。

我已经设法获得了颜色条,但我想要的刻度只是没有出现。这里的任何帮助将非常感激,因为我在尝试和搜索后被困在它几个小时。 这是我用于在底图上使用hexbin生成热图的代码。

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.colors import LinearSegmentedColormap
from matplotlib import cm

#Loading data from CSV file
DATA_FILE = '....../Population_data.csv'
roc_data = pd.read_csv(DATA_FILE)
roc_data.head()

#Creating figure window
fig = plt.figure(figsize=(14,10))
ax = fig.add_subplot(111)

#Drawing the basemap
m = Basemap(projection='merc', lat_0=43.12, lon_0=-77.626,
resolution = 'i',llcrnrlon=-78.236, 
                llcrnrlat=42.935,
                urcrnrlon=-77.072, 
                urcrnrlat=43.349)
m.drawcoastlines()
m.drawcounties(zorder=20, color='red')
m.drawcountries()
m.drawmapboundary()

#plotting the heatmap using hexbin
x, y = m(roc_data['Longitude'].values, roc_data['Latitude'].values)
values = roc_data['Total(20-64)']
m.hexbin(x, y, gridsize = 125, bins = 'log', C = values, cmap = cm.Reds)


#Defining minimum, mean and maximum population values
max_p = roc_data['Total(20-64)'].max()
min_p = roc_data['Total(20-64)'].min()
mean_p = roc_data['Total(20-64)'].mean()

#Adding Colorbar
cb = m.colorbar(location = 'bottom', format = '%d', label = 'Population by Census Blocks')

#setting ticks

#cb.set_ticks([48, 107, 1302])                #First approach, didn't work 
#cb.set_ticklabels(['Min', 'Mean', 'Max'])

cb.set_ticks([min_p, mean_p, max_p])          #Second appraoch, assumed ticks and tick labels should be same
cb.set_ticklabels([min_p, mean_p, max_p])     #from the above mentioned stackoverflow question, but did't work

plt.show()

通过使用第一种或第二种方法获得的彩色条形码得到的输出是相同的。它就像这里: Heatmap and colorbar with no ticks and labels

我希望最小,中位数和最大人口值(48,107和1302)显示在颜色条上,标签为Min,Mean和Max。谢谢你的时间

1 个答案:

答案 0 :(得分:0)

使用模式hexbin绘制bins = 'log'绘图时,将使用对数缩放绘制颜色。这意味着,如果数据最小值,平均值和最大值为minmeanmax,则对数缩放颜色条上的值为log10(min)log10(mean)log10(max)

因此需要使用日志值设置颜色条上的刻度。 tick标签可以设置为任何值。但是,我认为只是简单地说出像#34;意思是"在对数尺度上可能没有太多的信息。

一个特殊之处是颜色条的最小值实际上是log10(min+1)+1是由于日志低于1而导致的。

这是一个完整的例子。

enter image description here

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
from mpl_toolkits.basemap import Basemap
from matplotlib import cm

lon = -78.236+np.random.rand(1000)*(-77.072+78.236)
lat = 42.935 + np.random.rand(1000)*(43.349-42.935)
t = 99+np.random.normal(10,20,1000)
t[:50] = np.linspace(48,1302)
roc_data = pd.DataFrame({'Longitude':lon, 'Latitude':lat, "T":t })


#Creating figure window
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)

#Drawing the basemap
m = Basemap(projection='merc', lat_0=43.12, lon_0=-77.626,
resolution = 'i',llcrnrlon=-78.236, 
                llcrnrlat=42.935,
                urcrnrlon=-77.072, 
                urcrnrlat=43.349)
m.drawcoastlines()
m.drawcounties(zorder=20, color='red')
m.drawcountries()
m.drawmapboundary()

#plotting the heatmap using hexbin
x, y = m(roc_data['Longitude'].values, roc_data['Latitude'].values)
values = roc_data['T']
m.hexbin(x, y, gridsize = 125, bins = 'log', C = values, cmap = cm.Reds) #bins = 'log',

#Defining minimum, mean and maximum population values
max_p = roc_data['T'].max()
min_p = roc_data['T'].min()
mean_p = roc_data['T'].mean()
print [min_p, mean_p, max_p]
print [np.log10(min_p), np.log10(mean_p), np.log10(max_p)]

#Adding Colorbar
cb = m.colorbar(location = 'bottom', format = '%d', label = 'Population by Census Blocks') #format = '%d',

#setting ticks 
cb.set_ticks([np.log10(min_p+1), np.log10(mean_p), np.log10(max_p)])          
cb.set_ticklabels(['Min\n({:.1f})'.format(min_p), 'Mean\n({:.1f})'.format(mean_p), 'Max\n({:.1f})'.format(max_p)])
plt.tight_layout()
plt.show()