You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Matplotlib中对数轴指数的连字符转换为负号

解决Matplotlib对数刻度负号显示为连字符的问题

方案一:启用LaTeX渲染(适合学术场景)

如果你的环境支持LaTeX,启用它可以直接规范负号的显示,同时保留原有Unicode负号的禁用设置:

import matplotlib.pyplot as plt
import matplotlib

# 启用LaTeX渲染并禁用Unicode负号
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(10,7))
plt.plot(history_1.history['loss'], color='coral', label='Training loss')
plt.plot(history_1.history['val_loss'], color='firebrick', label='Testing loss')

plt.title('Training and testing loss in the function of epochs', fontsize=18)
plt.xlabel('Epochs', fontsize=15)
plt.yscale('log')
plt.ylabel('Loss', fontsize=15)

plt.legend(fontsize=15)
plt.grid()
plt.show()

方案二:自定义刻度格式化器(无额外依赖)

若无法使用LaTeX,可通过自定义格式化函数手动替换连字符为标准负号:

import matplotlib.pyplot as plt
import matplotlib
from matplotlib.ticker import ScalarFormatter

matplotlib.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(10,7))
plt.plot(history_1.history['loss'], color='coral', label='Training loss')
plt.plot(history_1.history['val_loss'], color='firebrick', label='Testing loss')

plt.title('Training and testing loss in the function of epochs', fontsize=18)
plt.xlabel('Epochs', fontsize=15)
plt.yscale('log')
plt.ylabel('Loss', fontsize=15)

# 自定义格式化器,替换连字符为标准负号
class CustomLogFormatter(ScalarFormatter):
    def format_data(self, value):
        return super().format_data(value).replace('-', '\u2212')

# 将格式化器应用到Y轴
plt.gca().yaxis.set_major_formatter(CustomLogFormatter())

plt.legend(fontsize=15)
plt.grid()
plt.show()

注意事项

  • 方案一渲染的负号更符合出版规范,但需要系统已安装LaTeX环境。
  • 方案二兼容性更强,无需额外依赖,适合快速解决问题。

内容的提问来源于stack exchange,提问作者TAKI DJEBBAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:25:39