当我绘制具有多个数据列的直方图时,当数据作为熊猫数据框给出时,图例显示正确,但当数据作为数组列表给出时,图例句柄的顺序似乎被翻转了。
例如这段代码:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
x1 = np.random.normal(100, 25, 100)
x2 = np.random.normal(200, 25, 100)
x3 = np.random.normal(300, 25, 100)
fig, axs = plt.subplots(1, 2, figsize=(18, 8))
df = pd.DataFrame(np.array([x1,x2,x3]).T, columns= ['x1', 'x2', 'x3'])
sns.histplot(df, bins=30, color=['r','g', 'b'], ax=axs[0])
sns.histplot([x1,x2,x3] , bins=30, color=['r','g', 'b'], ax=axs[1])
axs[1].legend(['x1','x2','x3'])
plt.show()
奇怪的是,如果我只是从轴上取下手柄并将其还给它,顺序是固定的。
axs[1].legend((axs[1].get_legend().legendHandles), ['x1','x2','x3'])