【问题标题】:How to use a discrete colorscale in plotly scattergeo usa map如何在 plotly scattergeo 美国地图中使用离散色标
【发布时间】:2021-11-14 09:12:21
【问题描述】:

我在使用 plotly(在 python 中)时尝试使用离散色阶。我需要一个离散色标,因为我为特定城市绘制的某些值与其他所有值相比太大了,因此离散色标可以帮助我轻松地可视化所有值。这是一个更好地解释我的情况的示例: 我有一个数据集,其中包含有关城市(美国)某些事件的详细信息。 该事件在纽约市发生了 50000 次,而在美国其他城市,同一事件发生的次数不到 1000 次。当我使用连续色阶时,所有其他城市的值都会下降到低端,而 NYC 是唯一使用色阶顶部颜色的值。

提前感谢您的帮助! 此致, 里沙布

【问题讨论】:

    标签: python plotly


    【解决方案1】:

    对于多个商店的 10 个不同的集群 ID,这就是我生成 10 个离散的自定义色阶的方式:

    import matplotlib
    
    def matplotlib_to_plotly(cmap, pl_entries):
    # Converts matplotlib colormap to plotly colormap. It also shuffles the color map
    
        h = 1.0/(pl_entries)
        pl_colorscale = []
        c_order = h * np.arange(pl_entries+1)
        c_order_shuffled = c_order.copy()
        # Shuffles the colormap
        np.random.shuffle(c_order_shuffled)
        for i in range(pl_entries):
            C = map(np.uint8, np.array(cmap(c_order_shuffled[i])[:3])*255)
            pl_colorscale.append([c_order[i], 'rgb'+str((C[0], C[1], C[2]))])
            # To have clear boundaries between colors in the colorbar
            if i < (pl_entries):
                 pl_colorscale.append([c_order[i+1], 'rgb'+str((C[0], C[1], C[2]))])
        return pl_colorscale
    
    # Sets the colormap of your choice 
    cmap = matplotlib.cm.get_cmap('jet')
    # Passes the number of distinct colors you need to generate. In this case we have 10 cluster ids in stores_info_df
    custom_colorscale = matplotlib_to_plotly(cmap, stores_info_df['CLUSTER_ID'].max())
    custom_colorscale
    

    然后,我在绘图函数中使用了上面的色标:

    def visualize_geo_store_clusters(stores_info_df, fig_name='store_similarity_US_map', cluster_id = 'CLUSTER_ID'):
    
        max_cluster_id = stores_info_df[cluster_id].max()
    
        data = [ dict(
            type = 'scattergeo',
            locationmode = 'USA-states',
            lon = stores_info_df['LONGTITUDE'],
            lat = stores_info_df['LATITUDE'],
            text = stores_info_df['TEXT'],
            mode = 'markers',
            marker = dict(
                colorscale= custom_colorscale, 
                cmin = stores_info_df[cluster_id].min(),
                color = stores_info_df[cluster_id],
                cmax = max_cluster_id,
                colorbar = dict(
                    title = 'Cluster ID',
                    titleside = 'top',
                    tickmode = 'array',
                    tickvals =  np.arange(1, max_cluster_id+1),
                    ticktext = np.arange(1, max_cluster_id+1),
                    #ticks = 'outside',
                )
    
            ))]
    
         layout = dict(
            title = 'Similarity between Stores',
            geo = dict(
                scope='usa',
                projection=dict( type='albers usa' ),
                showland = True,
                landcolor = "rgb(250, 250, 250)",
                subunitcolor = "rgb(217, 217, 217)",
                countrycolor = "rgb(217, 217, 217)",
                countrywidth = 0.5,
                subunitwidth = 0.5
            ),
        )
    
    fig = dict(data=data, layout=layout)
    plotly.offline.iplot(fig, validate=False)
    

    它会生成以下图。

    【讨论】:

      【解决方案2】:

      如果@Sahar 的答案为什么起作用不明显,您可以找到解决方案here

      您可以通过连续两次设置相同的参考点来创建具有不连续颜色的离散色标。

      这里我举一个例子,连续色标的创建与离散色标的创建有何不同。

      colors = ['red', 'green', 'blue']
      nc = len(colors)
      colorscale_continuous = tuple(zip(np.linspace(0, 1, nc), colors))
      colorscale_discrete = sorted(
          tuple(zip(np.linspace(0, 1 - 1/nc + 1e-6, nc), colors)) +
          tuple(zip(np.linspace(1/nc, 1, nc), colors)))
      

      (因素1e-6 只是为了断言正确的排序)

      最后,要使颜色条刻度在每个离散颜色上居中(请注意,这些刻度是垂直偏移/未对齐的,如@Sahar 的回答所示),向colorbar 提供以下参数:

      tickvals=np.linspace(1/nc/2, 1 - 1/nc/2, nc) * (nc - 1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-22
        • 1970-01-01
        • 2021-11-23
        相关资源
        最近更新 更多