python - 在 Geopandas 中更改颜色条

标签 python matplotlib geopandas

问题

如何访问绘制 GeoDataFrame 时创建的颜色条实例?在此示例中,我绘制了法国入侵俄罗斯期间的部队调动和规模,其中小于 10000 的军队规模以红色绘制。如何让颜色栏显示红色表示低于 10000?

MCVE:

import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from shapely.geometry import Point, LineString
import geopandas as gpd

# ingest troop movement data
PATH = ("https://vincentarelbundock.github.io/Rdatasets/csv/HistData/"
        "Minard.troops.csv")
troops = pd.read_csv(PATH)
troops['geometry'] = troops.apply(lambda row: Point(row.long, row.lat), axis=1)
troops = gpd.GeoDataFrame(troops)

# get army group paths
grouped = troops.groupby('group')
groups = [[LineString(group[['long', 'lat']].values), name]
          for name, group in grouped]
groups = pd.DataFrame(groups, columns=['geometry', 'army group'])
groups = gpd.GeoDataFrame(groups)
groups.plot(color=['red', 'green', 'blue'], lw=0.5)

# plot troop sizes
cmap = mpl.cm.get_cmap('cool')
cmap.set_under('red')
troops.plot(column='survivors', ax=plt.gca(),
            cmap=cmap, vmin=10000, legend=True, markersize=50)

输出:

enter image description here

这里,最后一行的 legend=True 添加了颜色条。

尝试解决方案

我知道如果我自己制作颜色条,我可以传递参数 extend='min' 以在颜色条的底部添加一个红色三角形。

而且我知道我可以通过颜色条轴(如 this answer 中的建议):

cax = plt.gcf().axes[1]

但我不知道这如何帮助我编辑颜色栏。我什至无法使用 cax.set_label('troop size') 添加标签。 (即,尽管 cax.get_label() 确实返回“部队规模”,但我在任何地方都看不到该标签)

这些轴似乎由两个多边形组成:

In[315]: cax.artists
Out[315]: 
[<matplotlib.patches.Polygon at 0x1e0e73c8>,
 <matplotlib.patches.Polygon at 0x190c8f28>]

不知道该怎么做。即使我能找到实际的 colorbar 实例,我也不知道如何将它扩展为 docs for the Colorbar class别提那样的话。

备选方案

  1. 有没有办法通过 GeoDataFrame.plot 函数传递 extend 关键字?

  2. 我能否通过在绘图时保存它或在图中找到它来以某种方式访问​​颜色条实例?

  3. 我该如何直接使用 Matplotlib 构建颜色条?如果更改参数,如何避免它偏离情节?

最佳答案

有一个问题(和 PR)可以将关键字传递给颜色栏构造:https://github.com/geopandas/geopandas/issues/697 .
但就目前而言,我认为最好的解决方法是自己创建颜色条:

创建相同的图,但使用 legend=False:

cmap = mpl.cm.get_cmap('cool')
cmap.set_under('red')
ax = troops.plot(column='survivors', cmap=cmap, vmin=10000, legend=False, markersize=50)

现在,我们获取为点创建的集合(来自散点图)作为 ax.collections 的第一个元素,因此我们可以指示 matplotlib 基于此映射创建颜色条(现在我们可以传递额外的关键字):

scatter = ax.collections[0]
plt.colorbar(scatter, ax=ax, extend='min')

这给了我

enter image description here

关于python - 在 Geopandas 中更改颜色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885589/

相关文章:

python - 通过 Python 计算两个字符串变量之间的公共(public)条目

Python JSONPath 过滤器表达式错误,jsonpath-rw 1.4.0 的意外字符

python - matplotlib.image.NonUniformImage 在 pdf 导出期间超出绘图区域

python - 如何在极坐标图中正确显示颜色条(半圆的等高线图)?

python - 许多二维点之间的最短路径(Shapely LineString 中的旅行商?)

python - 我正在用 plotly express 制作等值线图。如何将我的 csv 数据框中的值与 geojson 文件中的国家相匹配?

Python Socket(简单服务器脚本)

python - 为什么字符串会导致整个 pandas DataFrame 成为非数字?

python - 如何删除 Pandas 中的图例

python - geopandas 中 shapely 的缩放函数返回相似大小的点