从pandas datafram创建绘图scattermapbox

2024-05-07 23:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为印度尼西亚创建一个scattermapbox,用于在区域基础上进行各种统计(人口、国内生产总值等)。 我正在使用来自github的geopandas文件。在

plotly网站上的example为每个层创建多个文件,然后使用github链接作为源。在

#republican counties
source = 'https://raw.githubusercontent.com/plotly/datasets/master/florida-red-data.json'  
#democrat counties
source = 'https://raw.githubusercontent.com/plotly/datasets/master/florida-blue-data.json'

因此,我的问题是,如何使用pandas数据帧为每个区域创建layer dict并将其用作源(也可以通过其他数据帧中的特定值为每个区域着色)。 如果这是不可能的,这是必要的,为每个地区创建一个单独的文件,我该怎么做?我的尝试(第16-20行)似乎行不通

^{pr2}$

谢谢你的帮助!在


Tags: 文件httpsgithubmastercomjson区域source
1条回答
网友
1楼 · 发布于 2024-05-07 23:11:41

好吧,花了我一段时间,但我都想明白了。非常感谢Emma Grimaldi在中Vince Pota。他们的帖子帮助我度过了大部分时间。 我自己的问题的答案如下:

  1. 不需要为每个区域创建单独的文件。一、 你可以使用pandas dataframe来匹配json中区域的名称,这样就可以了。在

with open('indonesia-en.geojson') as f: geojson = json.load(f)

def make_sources(downsample = 0):
    sources = []
    geojson_copy = copy.deepcopy(geojson['features']) # do not overwrite the original file
    for feature in geojson_copy:

        if downsample > 0:
            coords = np.array(feature['geometry']['coordinates'][0][0])
            coords = coords[::downsample]
            feature['geometry']['coordinates'] = [[coords]]

        sources.append(dict(type = 'FeatureCollection',
                            features = [feature])
                      )
    return sources

因此,您只需从geojson中提取坐标并将其附加到dict列表[{}]。在

  1. 如何使用此列表动态创建层:
^{pr2}$

所以这里的解决方案太设置了sources = sources[k],即在make_sources()中创建的lat/long值dict的列表

  1. 如何相应地为图层着色color=scatter_colors[k]

在这个链接的例子中,我使用了3个函数

3.1scalarmappable

#sets colors based on min and max values
def scalarmappable(cmap, cmin, cmax):
        colormap = cm.get_cmap(cmap)
        norm = Normalize(vmin=cmin, vmax=cmax+(cmax*0.10)) #vmax get's increased 10 percent because otherwise the most populous region doesnt get colored
        return cm.ScalarMappable(norm=norm, cmap=colormap)

3.2scatter_colors

#uses matplotlib to create colors based on values and sets grey for isnan value
def get_scatter_colors(sm, df):
grey = 'rgba(128,128,128,1)'
return ['rgba' + str(sm.to_rgba(m, bytes = True, alpha = 1)) if not np.isnan(m) else grey for m in df]  

3.3colorscale

#defines horizontal range and corresponding values for colorscale
def get_colorscale(sm, df, cmin, cmax):
    xrange = np.linspace(0, 1, len(df))
    values = np.linspace(cmin, cmax, len(df))

    return [[i, 'rgba' + str(sm.to_rgba(v, bytes = True))] for i,v in zip(xrange, values) ]

然后使用函数设置变量

#assigning values
colormap = 'nipy_spectral'
minpop = stats['population'].min()
maxpop = stats['population'].max()
sources = make_sources(downsample=0)
lons, lats = get_centers()

sm = scalarmappable(colormap, minpop, maxpop)
scatter_colors = get_scatter_colors(sm, stats['population'])
colorscale = get_colorscale(sm, stats, minpop, maxpop)
hover_text = get_hover_text(stats['population'])

因此,如果有人对这个答案有什么问题,可以帮助你进步:)

相关问题 更多 >