【问题标题】:Same size on figure and colorbar [duplicate]图和颜色条上的大小相同[重复]
【发布时间】:2019-08-20 07:46:06
【问题描述】:

我简单地绘制了一个拟合文件,并在右侧绘制了一个颜色条。我无法调节图像和颜色条的大小,我希望它们大小相同。 此外,我想知道如何更改颜色条的标签,例如我通常在简单绘图上使用的 ax0.set_xticks()ax0.set_xticklabels()

这是代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from astropy.io import fits
import copy
from astropy.wcs import WCS
from astropy.utils.data import get_pkg_data_filename
from matplotlib.colors import LogNorm, Normalize
from regions import read_ds9

fits_file = "fb.fits"
hdul = fits.open(fits_file)
image_data = hdul[0].data
wcs = WCS(hdul[0].header)
hdul.close()

fig = plt.figure(figsize=(8,8))
ax0=fig.add_subplot(111, projection=wcs)

norm = LogNorm(10,1)
my_cmap = copy.copy(matplotlib.cm.get_cmap('Blues_r'))
my_cmap.set_bad((0,0,0))
im = ax0.imshow(image_data, cmap=my_cmap, norm=norm)
bar = fig.colorbar(im)


reg_file = "astropy.reg"
regs = read_ds9(reg_file, errors='warn')
for i, reg in enumerate(regs):
    reg.plot(ax=ax0)

ax0.set_title('')
ax0.set_xlabel('RA')
ax0.set_ylabel('DEC')
fig.tight_layout(rect=[0.08, 0.08, 0.94, 0.9])

plt.show()

最后的图片:

【问题讨论】:

    标签: python matplotlib astropy


    【解决方案1】:

    您可以使用shrink 作为颜色条的参数。 来自the docs

    shrink 乘以颜色条大小的分数

    查看链接,其他选项也是可能的,例如设置填充或纵横比。

    这样的事情可能对你有用:

    bar = fig.colorbar(im, shrink=0.8)
    

    您可以在您的颜色条所在的坐标区对象上使用set_yticklabels(您可以使用bar.ax 获得它)。如果您想自己指定刻度标签,请不要忘记首先指定刻度位置。

    比如:

    # `myticklocs` are the locations and `mylabels` are your labels
    bar = fig.colormap(im, ticks=myticklocs)
    bar.ax.set_yticklabels(mylabels, weight='bold', size=9)
    

    看看最小的official labelling demo

    【讨论】:

    • 你拼错了shrink
    • bar.ax.set_yticklabels() 不起作用...它覆盖了新标签...
    • @Bazingaa 谢谢!修复。糟糕的是,这不支持flake8 :)
    • 我无法删除标签...我尝试使用 bar.ax.set_yticklabels([])bar.ax.set_yticklabels([]) 没有成功。
    猜你喜欢
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2020-05-16
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多