如何在 matplotlib 条形图中用希腊符号替换主轴和副轴的图例标签?

How to replace legend labels with Greek symbols for primary and secondary axis in a matplotlib bar plot?

我有一个 6 列的数据框,我想将其绘制为条形图。 最后 3 列位于辅助轴上。出现在图上的默认图例是列名。但我需要将图例改为希腊符号。尝试这样做时,我遇到了两个问题:

  1. 当我使用 plt.legend 添加新的图例名称时,它没有更改现有的图例框,而是添加了一个新的。
  2. 当我尝试更改所有图例时,它只会更改次轴上的图例(最后 3 列数据),但不会更改绘制在左轴上的数据。

有没有办法解决这些问题?

此外,我如何指定左右 y 轴限制,间距均匀(或指定间距,如果可能的话)并且 y 轴刻度字体大小和粗细?

这是一个示例代码:

import pandas as pd 
import matplotlib.pyplot as plt


# To set plotting style
plotStyleDict = {'axes.titlesize' : 18,
'axes.titleweight' :'bold',
'axes.labelsize' : 15,
'lines.linewidth' : 3,
'lines.markersize' : 10,
'xtick.labelsize' : 12,
'ytick.labelsize' : 12}

plt.style.use(plotStyleDict)

# data dictionary
dataDict = {'Year': ['1st Year','2st Year','3rd Year','4th Year'],
            'ERRh': [0, 0.71, 0.46, 0.35],
            'HRRh': [0.0, 0.66, 0.33, 0.14],
            'EREh': [0.0, 0.38, 0.20, 0.11],
            'ERRc': [1.2, 1.62, 2.04, 0.04],
            'EREc': [1.5, 1.4, 1.3, 1.1],
            'HRRc': [1.36, 2.27, 4.83, 0.09]}

# create dataframe
dfDataTest=pd.DataFrame.from_dict(dataDict, orient='columns', dtype=None, columns=None)
dfDataTest.index = dfDataTest.Year
dfDataTest.drop('Year', inplace = True, axis=1)
print(dfDataTest)


# Bar plot  the dataframe with last 3 columns being on secondary axis
ax1 = dfDataTest [['ERRh', 'HRRh','EREh','ERRc', 'EREc', 'HRRc']].\
                              plot(kind='bar',color=['green','darkgreen','orange','blue','red','firebrick'], 
                              figsize=(16,6), edgecolor=['black','black','black','black','black','black'],
                              stacked=False, secondary_y= ['ERRc', 'EREc', 'HRRc'])

plt.xticks(rotation=30, horizontalalignment="center")
plt.title("Energy & Hydraulic Recoveries for Heating and Cooling",fontsize=18, weight='bold')

# specify left and right y labels with Greek symbols
ax1.set_ylabel(r'$\eta_{ER,h} , \eta_{HR,h}  , \eta_{th,h}   [-]$')
ax1.right_ax.set_ylabel(r'$\eta_{ER,c} , \eta_{HR,c}  , \eta_{th,c}  [-]$')

# change legends to Greek symbols
plt.legend([r'$\eta_{ER,h}$', r'$\eta_{HR,h}$', r'$\eta_{th,h}$',r'$\eta_{ER,c}$',
            r'$\eta_{HR,c}$',r'$\eta_{th,c}$'],loc=2)


plt.grid(True)
    
plt.show()

使用前plt.legend绘图结果如下:

使用plt.legend绘图结果如下:

我希望只有一个图例框(最好是右上角的那个),所有图例都替换为希腊符号。

感谢帮助!!

如果在绘图之前重命名数据框会更容易:

orig_cols = ['ERRh', 'HRRh','EREh','ERRc', 'EREc', 'HRRc']
rename_cols = [r'$\eta_{ER,h}$', r'$\eta_{HR,h}$', r'$\eta_{th,h}$',r'$\eta_{ER,c}$',
             r'$\eta_{HR,c}$',r'$\eta_{th,c}$']
rename_dict = dict(zip(orig_cols, rename_cols))
# Bar plot  the dataframe with last 3 columns being on secondary axis
ax1 = dfDataTest [orig_cols].rename(columns=rename_dict).\
                              plot(kind='bar',color=['green','darkgreen','orange','blue','red','firebrick'], 
                              figsize=(16,6), edgecolor=['black','black','black','black','black','black'],
                              stacked=False, secondary_y= [r'$\eta_{ER,c}$',
             r'$\eta_{HR,c}$',r'$\eta_{th,c}$'])

输出: