Python Matplotlib 中文显示问题:AttributeError: Line2D.set() got an unexpected keyword argument 'fontproperties'

在使用 Python 的 Matplotlib 库进行绘图时,如果直接在 plt.plot() 函数中使用 fontproperties 参数设置字体,会导致 AttributeError: Line2D.set() got an unexpected keyword argument 'fontproperties' 错误。

这是因为 plt.plot() 函数不支持直接设置 fontproperties 参数。

为了解决这个问题,并正确显示中文字符,我们可以使用以下两种方法:

方法一:使用 matplotlib.rcParams 设置全局字体

我们可以使用 matplotlib 库的 rcParams 来设置全局字体,这样就不需要在每个图形中都指定字体了。

以下是一个示例代码:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima.model import ARIMA

# 设置合适的字体
font_path = 'C:/Windows/Fonts/simsun.ttc'  # 修改为你系统中合适的字体路径
font_prop = fm.FontProperties(fname=font_path)

# 读取数据
data = pd.read_excel('D:\\M_hua\\text.xlsx', index_col=0, header=None, skiprows=[0])
data = data.astype(float)

# 平稳性检验
def check_stationarity(series):
    result = adfuller(series)
    print('ADF检验结果:')
    print('ADF Statistic:', result[0])
    print('p-value:', result[1])
    print('Critical Values:')
    for key, value in result[4].items():
        print(f'{key}: {value}')

# 查看原始数据的平稳性
print('原始数据的平稳性检验结果:')
check_stationarity(data.iloc[:, 0])

# 进行差分处理,直至平稳
diff_count = 0
while not adfuller(data.iloc[:, 0])[1] < 0.05:
    data = data.diff().dropna()
    diff_count += 1

# 查看差分后数据的平稳性
print(f'经过{diff_count}阶差分后数据的平稳性检验结果:')
check_stationarity(data.iloc[:, 0])

# 构建ARIMA模型,并拟合数据
model = ARIMA(data, order=(1, 0, 1))
result = model.fit()

# 输出模型系数
print('模型系数:')
print(result.summary().tables[1])

# 设置全局字体
plt.rcParams['font.sans-serif'] = ['SimSun']

# 可视化拟合结果
plt.plot(data, label='差分后数据')
plt.plot(result.fittedvalues, color='red', label='拟合结果')
plt.legend()
plt.show()

方法二:在 plt.legend() 函数中设置字体

如果只想在图例中使用中文字体,可以在调用 plt.legend() 函数时,使用 prop 参数指定字体属性。

# ... 其他代码 ...

# 可视化拟合结果
plt.plot(data, label='差分后数据')
plt.plot(result.fittedvalues, color='red', label='拟合结果')
plt.legend(prop=font_prop)  # 在 plt.legend() 中设置字体
plt.show()

请根据你的实际需求选择合适的方法。

注意:

  • 你需要将代码中的字体路径 'C:/Windows/Fonts/simsun.ttc' 修改为你系统中合适的字体路径。
  • 确保你安装了所需的库,例如 pandas、matplotlib、statsmodels 等。

希望这些信息能帮助你解决问题!

Python Matplotlib 中文显示问题:AttributeError: Line2D.set() got an unexpected keyword argument 'fontproperties'

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

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