Geopandas绘图:色条文本格式设置与最小亮度调整问题
Geopandas绘图:色条格式调整与最小亮度设置
一、解决色条文本格式问题(添加美元符号$和千分位分隔符)
1. 使用scheme='quantiles'时的报错修复
设置fmt='$%d'触发ParseException,是因为matplotlib会把$解析为数学公式起始符号,导致语法错误。解决方式是改用自定义格式化函数:
import matplotlib.ticker as ticker # 自定义格式化函数,同时添加$和千分位 def dollar_format(x, pos): return f"${int(x):,}" 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", 'fmt': dollar_format # 传入自定义函数 }, edgecolor='black', cmap='Blues', missing_kwds={'color': 'lightgrey'}).set_axis_off()
2. 不使用分位数分组(scheme=None)时的千分位实现
直接用'$%d'只能添加美元符号,无法实现千分位。可以借助matplotlib.ticker.StrMethodFormatter来处理:
import matplotlib.ticker as ticker 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') sccounties.plot(column='Grant Funds Disbursed', legend=True, legend_kwds={"label":"2024 Rural Infrastructure Fund Grants", 'orientation':'horizontal', 'format': ticker.StrMethodFormatter("${x:,.0f}") # 同时实现$和千分位 }, cmap='Blues', edgecolor='black', missing_kwds={'color': 'lightgrey'}).set_axis_off()
${x:,.0f}说明:x指代数值,,.0f表示保留0位小数并添加千分位分隔符,前缀$实现美元符号格式。
二、设置最小亮度,让$0区域呈现淡蓝色
默认情况下0值区域会显示色条最浅色(接近白色),可以通过两种方式调整:
方法1:使用归一化范围调整
通过Normalize设置vmin为略小于0的值,让0对应色条中偏浅的蓝色:
import matplotlib.colors as colors max_value = sccounties['Grant Funds Disbursed'].max() # 设置vmin为-1,使0值对应色条中偏浅的蓝色 norm = colors.Normalize(vmin=-1, vmax=max_value) sccounties.plot(column='Grant Funds Disbursed', legend=True, legend_kwds={"label":"2024 Rural Infrastructure Fund Grants", 'orientation':'horizontal', 'format': ticker.StrMethodFormatter("${x:,.0f}") }, cmap='Blues', norm=norm, # 应用归一化规则 edgecolor='black', missing_kwds={'color': 'lightgrey'}).set_axis_off()
方法2:截断色条起始部分
直接设置色条的最小值对应颜色,让0值显示淡蓝色:
import matplotlib.pyplot as plt cmap = plt.get_cmap('Blues') # 取色条10%位置的颜色作为0值的显示色 cmap.set_under(cmap(0.1)) sccounties.plot(column='Grant Funds Disbursed', legend=True, legend_kwds={"label":"2024 Rural Infrastructure Fund Grants", 'orientation':'horizontal', 'format': ticker.StrMethodFormatter("${x:,.0f}") }, cmap=cmap, vmin=0, # 设定数值最小值为0 edgecolor='black', missing_kwds={'color': 'lightgrey'}).set_axis_off()
内容的提问来源于stack exchange,提问作者Vijay Tripathi
相关产品推荐
相关产品推荐

