更改 matplotlib 和底图上的点颜色不起作用

Changing point color on matplolib and basemap not working

我在使用 Basemap 将数据放到地图上并让这些点改变颜色时遇到了一些问题。我已经在网上阅读了很多关于如何执行此操作的不同内容,但我仍然得到一张没有分数的地图。这是我的代码:

import pandas as pd
import numpy as np
import pickle
from IPython.display import SVG, display_svg
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as co

d3data = pickle.load( open( "9_28_2015to10_04_2015.pickle", "rb" ) )

lons = d3data['longitude'].tolist()
lats = d3data['latitude'].tolist()
normcts = co.Normalize(d3data['GrossCounts'])

plt.figure(figsize=(20,10))

m = Basemap(projection='cass', lat_0 = 40.108004, lon_0 = -88.228878,
    resolution = 'h', area_thresh = 0.1,
    llcrnrlon=-88.238399, llcrnrlat=40.097942,
    urcrnrlon=-88.219345, urcrnrlat=40.116158)

m.drawcountries()
m.fillcontinents(color='white')
m.drawmapboundary()
m.readshapefile('mhj_shapes/lines', 'lines')
cmap = plt.cm.RdYlBu_r
norm = co.Normalize(vmin=d3data['GrossCounts'].min(),
    vmax=d3data['GrossCounts'].max())
pointcolors = plt.cm.ScalarMappable(norm, cmap)

for i in range(0, len(d3data)): 
    col = pointcolors.to_rgba(d3data['GrossCounts'][i])
    x,y = m(d3data['longitude'][i],d3data['latitude'][i])
    m.scatter(x, y, marker = 'o', s=10, color=col, cmap=cmap)

plt.show()

我的问题是我的形状文件生成的地图很好,但我没有在它上面得到任何点。我想在地图顶部绘制数据框列 d3data['GrossCounts'],并使色标的(整数)值为 d3data['GrossCounts']

如有任何建议,我们将不胜感激!

如果没有您的 data/shape 文件等,很难进行测试,但问题可能出在您的 for 循环上。也许不使用循环试试:

col = pointcolors.to_rgba(d3data['GrossCounts'])
x, y = m(d3data['longitude'], d3data['latitude'])
m.scatter(x, y, marker='o', s=10, color=col, cmap=cmap)

即如果我这样做:

plt.figure(figsize=(8,5))

m = Basemap(projection='cass', lat_0 = 0, lon_0 = 0,
    resolution = 'l', area_thresh = 0.1,
    llcrnrlon=-10, llcrnrlat=-10,
    urcrnrlon=10, urcrnrlat=10)

m.drawcountries()
m.fillcontinents(color='white')
m.drawmapboundary()
#m.readshapefile('mhj_shapes/lines', 'lines')
cmap = plt.cm.RdYlBu_r

x, y = m([0, 5], [0, 5])
df = pd.DataFrame({'a': [1,2]})
norm = co.Normalize(vmin=df.a.min(), vmax=df.a.max())
pointcolors = plt.cm.ScalarMappable(norm, cmap)
col = pointcolors.to_rgba(df.a)
m.scatter(x, y, s=10, color=col)

plt.show()

我得到:

这就是你想要的吗?

问题解决了!

事实证明, 中对此进行了描述(尽管我在这里搜索时并未搜索正确的术语)。这是最终起作用的更改:

m.drawcountries()
m.fillcontinents(color='white', zorder=0) # <--zorder!!!
m.drawmapboundary()
m.readshapefile('mhj_shapes/lines', 'lines')
cmap = plt.cm.jet

x, y = m(lons, lats)
norm = co.Normalize(vmin=d3data.GrossCounts.min(), vmax=250)
pointcolors = plt.cm.ScalarMappable(norm, cmap)
col = pointcolors.to_rgba(d3data.GrossCounts)
m.scatter(x, y, s=10, c=col, cmap=plt.cm.jet)

我不知道为什么在我找到的任何在线示例中都没有看到 zorder,但是添加它可以确保将地图本身发送到后面,以便将点带到前面。谢谢大家的帮助!