Matplotlib 颜色图归一化与散点图的中点值

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

我正在使用 Python 中的 Matplotlib 和 Geopandas 在地图上创建散点图,但我面临着正确设置颜色条的问题。

我希望最大颜色条值为 3.95(对应于深红色),最小值为 -5.00(对应于深蓝色),零值为白色,表示数据的中点。

import matplotlib.pyplot as plt
import contextily as ctx

# Find the maximum absolute value for the color range to center it at zero
vmax = 5
vmin = -5

# Plotting with smaller points and a red-white-blue color scale centered at zero
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
scatter = ax.scatter(x=results_df.geometry.x, y=results_df.geometry.y,
                     c=results_df['Trend'], vmin=vmin, vmax=vmax, alpha=0.75, cmap='RdBu_r', s=20) 

# Create the colorbar
cbar = fig.colorbar(scatter, ax=ax, ticks=ticks, extend='min')

# Define the format of the tick labels, add a special label for the actual max if it's in the range
tick_labels = [f"{tick:.2f}" if tick != actual_max else f"Max: {tick:.2f}" for tick in ticks]
cbar.ax.set_yticklabels(tick_labels)

# Add text for actual min at the bottom of the colorbar
if actual_min < vmin:
    cbar.ax.text(0, -0.1, f"Min: {actual_min:.2f}", va='bottom', ha='center', transform=cbar.ax.transAxes)

# Add a background map
ctx.add_basemap(ax, crs=results_df.crs.to_string(), source=ctx.providers.OpenStreetMap.Mapnik)

# Set axis limit to limit the display area
ax.set_xlim([results_df.total_bounds[0], results_df.total_bounds[2]])
ax.set_ylim([results_df.total_bounds[1], results_df.total_bounds[3]])

plt.show()

enter image description here

我利用 Matplotlib 的 TwoSlopeNorm 尝试将颜色图的中点设置为零。这应该将我的数据中的值 0 映射到“RdBu_r”颜色图中的白色。 我已在 TwoSlopeNorm 中显式设置 vmin、vcenter 和 vmax 参数,以将数据值与颜色图上所需的颜色对齐。 我已检查以确保数据不包含任何超出范围的值,这些值可能会导致颜色标准化倾斜。

python matplotlib jupyter-notebook colorbar
1个回答
0
投票

在图像中,看起来可能只有几个点 >0,因为只有少数点是红色的。几乎所有数据点都是蓝色的,表明数据大部分是<0. To me it seems like the skew is in the data, rather than a problem with the norm.

运行

results_df.Trend.gt(3).value_counts()
会告诉你有多少是明显红色的。与图中所示大致相符吗?

如果您发现红色的数量很大,则可能是它们在绘图上被蓝点覆盖(过度绘制),尽管这似乎不太可能。

© www.soinside.com 2019 - 2024. All rights reserved.