【问题标题】:How to change color bar to align with main plot in Matplotlib?如何更改颜色条以与 Matplotlib 中的主图对齐?
【发布时间】:2023-03-11 23:55:01
【问题描述】:

在 Matplotlib 中使用 imshow 绘制矩阵时,colorbar 图例条的大小、位置、字体等参数如何更改?

这里我创建了一个示例代码

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline

def plot_matrix(mat, title='example', cmap=plt.cm.Blues):
    plt.imshow(mat, interpolation='nearest', cmap=cmap)
    plt.grid(False)
    plt.title(title)
    plt.colorbar()

data = np.random.random((20, 20))

plt.figure(figsize=(8,8))
plt.tick_params(axis='both', which='major', labelsize=12)

plot_matrix(data) 

在一个真实的用例中,我得到了复杂的标签,图例栏变得比矩阵本身高得多。我想更改图例栏以使情节更有效地利用空间。

我为matplotlib.pyplot.colorbar 找到了documentation,但是还没有找到设置颜色图例栏的大小、位置和字体大小的好方法。

【问题讨论】:

  • 你有很多使用make_axes_locatable, as detailed here的可能性
  • +1, make_axes_locatable 方法在绘图时计算轴的位置和大小。或者,我们可以在绘制时间之前指定轴的位置和大小。见下文:

标签: python numpy pandas matplotlib plot


【解决方案1】:

imshow 强制执行 1:1 方面(默认情况下,但您可以使用 aspect 参数更改它),这使事情变得有点棘手。为了始终获得一致的结果,我可能会建议手动指定轴的大小:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline

def plot_matrix(mat, figsize, title='example', cmap=plt.cm.Blues):
    f = plt.figure(figsize=figsize)
    ax = plt.axes([0, 0.05, 0.9, 0.9 ]) #left, bottom, width, height
    #note that we are forcing width:height=1:1 here, 
    #as 0.9*8 : 0.9*8 = 1:1, the figure size is (8,8)
    #if the figure size changes, the width:height ratio here also need to be changed
    im = ax.imshow(mat, interpolation='nearest', cmap=cmap)
    ax.grid(False)
    ax.set_title(title)
    cax = plt.axes([0.95, 0.05, 0.05,0.9 ])
    plt.colorbar(mappable=im, cax=cax)
    return ax, cax

data = np.random.random((20, 20))
ax, cax = plot_matrix(data, (8,8)) 

现在您有了绘制颜色条的轴cax。你可以做很多事情,比如旋转标签,使用plt.setp(cax.get_yticklabels(), rotation=45)

【讨论】:

  • 感谢 CT!我按照您的方式实现了我的方法,并且效果很好。条形尺寸对齐良好。我还可以在创建 x 和 y 刻度时设置它们的字体大小。另一件事我还想设置彩条标签的字体。有什么建议吗?
  • 不客气!更改字体为:plt.setp(cax.get_yticklabels(), fontname='Times New Roman') 假设您的盒子上安装了Time New Roman
猜你喜欢
  • 2020-04-12
  • 2021-05-01
  • 2021-01-07
  • 2017-11-24
  • 2017-01-22
  • 2015-03-21
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
相关资源
最近更新 更多