0

I want to modify the text format of the colour bar in my Geopandas plot, to include a $ and a comma thousands separator. I also want to set a minimum lightness so that there is still a hint of blue for areas representing the minimal value (i.e., $0).

grants24 = pa24.groupby(by='County')['Grant Funds Disbursed'].sum().reset_index()
County
Allendale              0
Anderson         1600000
Beaufort           50000
Berkeley               0
Charleston             0
Cherokee          200000
Chester          1131481
Chesterfield      550000
Clarendon         250000
Colleton          249656
Darlington             0
Dorchester        500000
Edgefield              0
Florence          500000
Greenville        100000
Horry                  0
Jasper             50000
Lancaster              0
Laurens                0
Marlboro               0
McCormick         340000
Orangeburg        100000
Pickens                0
Richland          550000
Spartanburg       100000
Sumter          13000000
Williamsburg      100000
York                   0
Name: Grant Funds Disbursed, dtype: Int64

sccounties = gpd.read_file('SC-45-south-carolina-counties.json')
sccounties = sccounties.merge(grants24, left_on='NAME', right_on='County', how='left')

sccounties.plot(column='Grant Funds Disbursed', 
                scheme='quantiles',
                legend=True,
                legend_kwds={'title':"2024 Rural Infrastructure Fund Grants",
                            # 'orientation':'horizontal',
                             'fmt':'$%d'
                             }, 
                edgecolor='black',
                cmap='Blues',
                missing_kwds={'color': 'lightgrey'}).set_axis_off()

Which results in the following error message:


Lib\site-packages\matplotlib\_mathtext.py:2173, in Parser.parse(self, s, fonts_object, fontsize, dpi)
   2170     result = self._expression.parseString(s)
   2171 except ParseBaseException as err:
   2172     # explain becomes a plain method on pyparsing 3 (err.explain(0)).
-> 2173     raise ValueError("\n" + ParseException.explain(err, 0)) from None
   2174 self._state_stack = []
   2175 self._in_subscript_or_superscript = False

Value Error
$%d, $%d
^
ParseException: Expected end of text, found '$'  (at char 0), (line:1, col:1)

I'd rather not plot quantiles/buckets (i.e., preferred schema None). When I plotted no schema and was able to include $ but not the thousands separator.

ruralinv24 = pa24[pa24['Fund Source Type']=='RIF'].groupby(by='County')['Grant Funds Disbursed'].sum().reset_index()

sccounties = gpd.read_file('SC-45-south-carolina-counties.json')
sccounties = sccounties.merge(ruralinv24, left_on='NAME', right_on='County', how='left')

# fig, ax = plt.subplots(1, 1)
sccounties.plot(column='Grant Funds Disbursed', 
                legend=True,
                legend_kwds={"label":"2024 Rural Infrastructure Fund Grants",
                             'orientation':'horizontal',
                             'format':'$%d'
                             }, 
                cmap='Blues',
                edgecolor='black',
                missing_kwds={'color': 'lightgrey'}).set_axis_off()

I tried 'format':['$%n']2 but it wasn't recognized, and I couldn't figure out how to set the minimum colour value either. enter image description here

Referenced these posts: Suppress scientific notation in geopandas plot legend [duplicate] and the geopandas plot() documentation

1 Answer 1

0

To set the appropriate colouring, you could try using matplotlib.colors, whereas for customizing the color bar try to change to matplotlib.ticker, since legend_kwds['format'] does not support the advanced formatting which you want to implement here:

import matplotlib.colors as mcolors
import matplotlib.ticker as mticker


def custom_format(value, tick_number):
    return f"${value:,.0f}"

base_cmap = plt.cm.Blues
custom_cmap = mcolors.LinearSegmentedColormap.from_list(
    "CustomBlues", 
    [(0.1, "lightblue"), (1, base_cmap(1.0))] 
)

fig, ax = plt.subplots(1, 1, figsize=(10, 6))
plot = sccounties.plot(
    column='Grant Funds Disbursed',
    cmap=custom_cmap,
    legend=True,
    edgecolor='black',
    missing_kwds={'color': 'lightgrey'},
    ax=ax
)

cbar = plot.get_figure().get_axes()[-1]
cbar.yaxis.set_major_formatter(mticker.FuncFormatter(custom_format))
cbar.set_title("2024 Rural Infrastructure Fund Grants", fontsize=10)

ax.set_axis_off()
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.