在使用 Matplotlib 绘制图表时,有时会出现中文标题显示为空的情况。这可能是由于中文字体的问题导致的。

为了解决这个问题,可以尝试添加以下代码来设置中文字体:

plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置中文字体为黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

完整代码如下:

import matplotlib.pyplot as plt

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# Data
month_number = list(range(1, 13))
total_profit = [2500, 2630, 2140, 3400, 3600, 2760, 2980, 3700, 3540, 1990, 2340, 2900]

# Plotting
plt.plot(month_number, total_profit, linestyle='dashed', color='red', marker='o', markersize=8, linewidth=3)

# Title and Labels
plt.title('图一:全年公司售卖数据')
plt.xlabel('Month Number')
plt.ylabel('Sold units number')

# Legend
plt.legend(['Total Profit'])

# Display plot
plt.show()

这样应该能够正确显示中文标题。

Matplotlib 中文标题显示问题解决方法 - 如何在 Python 图表中显示中文

原文地址: https://www.cveoy.top/t/topic/bQbq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录