gpt4 book ai didi

Python matplotlib : How to tick and ticklabel an axis/object independently of the object's scale

转载 作者:太空宇宙 更新时间:2023-11-03 15:53:41 26 4
gpt4 key购买 nike

下面的代码在图中定义了一个矩形区域,并根据其中的颜色图绘制了一个颜色条。我已将颜色条的缩放比例更改为其原始值的立方根,但我希望刻度线和刻度标签在条形长度上保持线性,因此它对于我的目的来说是正确的。如果可能的话,我不妨在那里画一条直线,然后将其线性渐变。我该如何处理这个问题? mpl 是 matplotlib,plt 是 pyplot。这个想法是为 choropleth(彩色世界地图)制作一个颜色条图例。

def draw_legend (clr_map):
""" Draw color bar legend ... (inspired by: http://ramiro.org/notebook/basemap-choropleth/) """
fig = plt.figure(figsize=(8,12))
ax_legend = fig.add_axes([0.26, -0.02, 0.48, 0.016], zorder=3)
grads = np.linspace(0.,1.,400)
bins = np.linspace(0.,1.,10)
scheme = [clr_map(i/400) for i in range(400)]
cmap = mpl.colors.ListedColormap(scheme)
cb = mpl.colorbar.ColorbarBase(ax_legend, cmap=cmap, ticks=bins, boundaries=grads**(1/3.), \
orientation='horizontal') # Before I'd done cmap as sqrt(): boundaries=np.sqrt(grads)
#cb.ax.set_xticks(bins)
cb.ax.set_xticklabels([str(round(i, 1)) for i in bins], fontsize=10);

draw_legend (plt.cm.plasma)

最佳答案

要设置颜色条上的刻度,您可以使用cb.set_ticks(bins**(1/3.))。您也可以直接缩放颜色图 (clr_map((i/400.)**(1./3)))。

import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.colorbar
import numpy as np

def draw_legend (clr_map):
""" Draw a color bar legend
with a qubic root colormap
"""
# Version 1, scale boundaries, set ticks to colorbar values
fig = plt.figure(figsize=(6,4))
ax_legend = fig.add_axes([0.26, 0.7, 0.48, 0.1], zorder=3)
ax_legend.set_title("Version 1\nscale boundaries, set ticks to colorbar values")
grads = np.linspace(0.,1.,400)
bins = np.linspace(0.,1.,11)
scheme = [clr_map(i/400.) for i in range(400)]
cmap = matplotlib.colors.ListedColormap(scheme)
cb = matplotlib.colorbar.ColorbarBase(ax_legend, cmap=cmap, ticks=bins, boundaries=grads**(1/3.), \
orientation='horizontal')

cb.set_ticks(bins**(1/3.))
cb.ax.set_xticklabels(bins**(1/3.), fontsize=10, rotation =45, ha="center")
cb.draw_all()

# Version 2, scale colormap, set ticks to arbitrary values
ax_legend2 = fig.add_axes([0.26, 0.27, 0.48, 0.1], zorder=3)
ax_legend2.set_title("Version 2\nscale colormap, set ticks to arbitrary values")
grads = np.linspace(0.,1.,400)
bins = np.linspace(0.,1.,11)
scheme = [clr_map((i/400.)**(1./3)) for i in range(400)]
cmap = matplotlib.colors.ListedColormap(scheme)
cb = matplotlib.colorbar.ColorbarBase(ax_legend2, cmap=cmap, ticks=bins,
orientation='horizontal')
cb.set_ticks(bins)
cb.draw_all()


draw_legend (plt.cm.jet)
plt.savefig(__file__+".png")
plt.show()

enter image description here

关于Python matplotlib : How to tick and ticklabel an axis/object independently of the object's scale,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com