Geopandas 颜色条文本的格式

问题描述 投票:0回答:1

我想修改

Geopandas
图中颜色条的文本格式,以包含 $ 和逗号千位分隔符。 我还想设置一个最小亮度,以便代表最小值(即 $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()

这会导致以下错误消息:


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)

我宁愿不绘制分位数/桶(即首选

schema
无)。 当我绘制没有
schema
并且能够包含 $ 但不包含千位分隔符时。

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()

我尝试了

'format':['$%n']
2但它没有被识别,而且我也不知道如何设置最小颜色值。 enter image description here

参考了这些帖子:在geopandas图例中抑制科学记数法[重复]geopandasplot()文档

matplotlib geopandas colorbar
1个回答
0
投票

要设置适当的颜色,您可以尝试使用

matplotlib.colors
,而要自定义颜色栏,请尝试更改为
matplotlib.ticker
, 因为
legend_kwds['format']
不支持您想要在此处实现的高级格式:

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()
© www.soinside.com 2019 - 2024. All rights reserved.