【问题标题】:Matplotlib, usetex: Colorbar's font does not match plot's fontMatplotlib,usetex:颜色栏的字体与绘图的字体不匹配
【发布时间】:2016-09-05 11:16:44
【问题描述】:

我有一个带有颜色条的 matplotlib 图,但似乎无法弄清楚如何匹配图的字体和颜色条。

我尝试使用 usetex 进行文本处理,但似乎只有绘图的刻度受到影响,而不是颜色条的刻度。 另外,我已经搜索了很多解决方案,因此在以下代码示例中,包含了一些不同的尝试,但结果仍然是粗体。最小失败代码示例:

import matplotlib as mpl
import matplotlib.pyplot as plt
import sys
import colorsys
import numpy as np


mpl.rc('text', usetex=True)
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.weight"] = 100
plt.rcParams["axes.labelweight"] = 100
plt.rcParams["figure.titleweight"] = 100


def draw():
    colors = [colorsys.hsv_to_rgb(0.33, step /15, 1) for step in [2, 5, 8, 11, 14]]
    mymap = mpl.colors.LinearSegmentedColormap.from_list('value',colors, N=5)

    Z = [[0,0],[0,0]]
    levels = range(2,15+4,3)
    CS3 = plt.contourf(Z, levels, cmap=mymap)
    plt.clf()

    plt.figure(figsize=(20, 15))
    plt.gca().set_aspect('equal')

    cbar = plt.colorbar(CS3, ax=plt.gca(), shrink=0.5, fraction=0.5, aspect=30, pad=0.05, orientation="horizontal")

    cbar.set_ticks([1.5 + x for x in [2,5,8,11,14]])

    # attempts to make the fonts look the same
    cbar.ax.set_xticklabels([1,2,3,4,5], weight="light", fontsize=16)
    cbar.set_label("value", weight="ultralight", fontsize=32)
    plt.setp(cbar.ax.xaxis.get_ticklabels(), weight='ultralight', fontsize=16)

    for l in cbar.ax.xaxis.get_ticklabels():
        l.set_weight("light")

    plt.show()

draw()

不幸的是,字体看起来完全不一样。图片:

我确定这只是我对 usetex 的愚蠢误解。为什么 usetex 似乎无法处理颜色图的字体?

谢谢!

【问题讨论】:

  • 复制此代码时出现错误。可能与我使用 OSX 和 python3 有关。
  • 示例在 OS X + Python 3 上运行良好
  • @Skirrebattie 我实际上也在使用 OS X + python 3。你得到什么错误?
  • 升级了matplotlib,错误消失了,现在出现与tex相关的错误。先重新安装mactex,看看会发生什么;)

标签: python matplotlib fonts styles tex


【解决方案1】:

这里的问题是,当 usetex=True 时,MPL 将刻度标签包装在 $ 中。这导致它们的大小与未包含在 $ 中的文本不同。当您强制将刻度标记为[1,2,3,4,5] 时,这些值不会包含在$ 中,因此呈现方式不同。我不知道为什么会这样的细节,但我自己遇到了这个问题。

我建议将您的颜色条刻度包裹在 $ 中,例如:

cbar.ax.set_xticklabels(['${}$'.format(tkval) for tkval in [1, 2, 3, 4, 5]])

从那里您应该能够弄清楚如何调整字体大小/粗细,以便它们匹配并得到您想要的。

【讨论】:

  • 就是这样!谢谢你,远方!
猜你喜欢
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多