Home > Net >  Plot the bar legend instead of ranges when using quantiles scheme in geopandas plot
Plot the bar legend instead of ranges when using quantiles scheme in geopandas plot

Time:10-14

Let's say I have the data and I use geopandas plot function to create the following map

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world['gdp_per_cap'] = world.gdp_md_est / world.pop_est
world.plot(column='gdp_per_cap', cmap = 'Blues', scheme='quantiles', k = 10,legend=True)
plt.show()

enter image description here

As you see it generates the legend with the range values. Is it possible to change this legend and plot the standard bar legend with different (sequantial) colours?

I know that the quantiles scheme creates the classes and you can't treat them as a continuous variable, but somehow it should still be possible to construct a bar legend similar to one when I delete scheme='quantiles', k = 10 from the code above.

Thanks for your help

CodePudding user response:

When qualitative colormap is needed for a thematic plot, one can find it plot1

If sequential colormap is used instead of qualitative colormap, the plot can be created similarly. Here I use Blues colormap. This is more appropriate for the GDP per capita data.

newPlot2

EDIT My apology for some errors on the code/map:- GPD ---> GDP

The legend's label texts can be accessed and edited as needed. Additional code for such operation follows:-

# Manipulate the legend's label texts
# Replace range_text with mid_range as new label texts
for eb in leg1.get_texts():
    txt = eb.get_text()
    low,high = [float(tt) for tt in  txt.split(sep=",")]
    avg = (low high)/2        # compute mid-range values
    #print(low,high,avg)
    eb.set_text(f"{avg:.2f}") # midrange values, 2 deci digits
    #eb.set_text(f"")         # blank-out text

The changes will be:

Old text         --> New text
  0.570,   1.655 --> 1.11
  1.655,   3.053 --> 2.35
  3.053,   4.813 --> 3.93
  4.813,   8.357 --> 6.58
  8.357,  11.620 --> 9.99
 11.620,  15.776 --> 13.70
 15.776,  24.574 --> 20.18
 24.574,  35.761 --> 30.17
 35.761,  48.513 --> 42.14
 48.513, 200.000 --> 124.26
  • Related