我在尝试修改Matplotlib图表标题颜色时遇到了困难。
我有一个包含多个子图的图表:
import matplotlib as mpl
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 4, sharex='all', sharey='all',
figsize=(20, 9), dpi=600)
这个图表由10个子图组成,每个子图上使用相同的符号标记数据点,因此我希望为整个图表创建一个联合图例,而不是为每个坐标轴单独设置。
我已经关闭了右上角和中间右边的坐标轴区域,打算在这片空白区域放置图例:
ax[0, 3].axis('off')
ax[1, 3].axis('off')
接下来,我创建了用于图例的元素:
legend_elements = [Line2D([0], [0], marker='x', color='w', markeredgecolor='b', label='测量数据点'),
Line2D([0], [0], marker='o', color='w', markeredgecolor='g', label='数据点均值'),
Line2D([0], [0], color='r', label='模型拟合曲线')]
但在编写图例时,我发现更改图例标题文本颜色极其困难。我尝试了几种方法:
legend = fig.legend(handles=legend_elements, fontsize=10, labelcolor='c',
loc='lower left', bbox_to_anchor=(0.77, 0.63, 1, 1))
legend.set_title('图例\n', color='c')
# 报错:TypeError: Legend.set_title() got an unexpected keyword argument 'color'
...
legend = fig.legend(handles=legend_elements, fontsize=10, labelcolor='c',
loc='lower left', bbox_to_anchor=(0.77, 0.63, 1, 1),
title='图例\n', title_fontsize=10)
plt.setp(legend.get_title(), color='c')
# 报错:AttributeError: 'NoneType' object has no attribute 'get_title'
...
fig.setp(legend.get_title(), color='c')
# 报错:AttributeError: 'Figure' object has no attribute 'setp'
...
legend._legend_title_box._text.set_color('c')
# 报错:AttributeError: 'NoneType' object has no attribute '_legend_title_box'
我还研究了matplotlib.font_manager.FontProperties
,考虑使用类似的方法,但是据我所知,FontProperties并没有直接提供颜色关键字参数:
import matplotlib.font_manager as font_manager
legend_title_props = font_manager.FontProperties(color='c')
legend = fig.legend(handles=legend_elements, fontsize=10, labelcolor='c',
loc='lower left', bbox_to_anchor=(0.77, 0.63, 1, 1),
title='图例\n', title_fontsize=10,
title_fontproperties=legend_title_props)
# 报错:TypeError: FontProperties.__init__() got an unexpected keyword argument 'color'
我找不到任何在线解决方案。我有种感觉,问题可能源自于我的图例对象被存储为'NoneType'对象,但我无法弄清楚是什么原因导致了这个问题。不知道有没有人知道解决办法?