Легенды и маркеры не отображаются правильно в подграфикахPython

Программы на Python
Anonymous
Легенды и маркеры не отображаются правильно в подграфиках

Сообщение Anonymous »

У меня есть несколько рисунков с подграфиками, на которых я сравниваю различные параметры двух тестов (файлы Excel Testdata1 и Testdata2). Поскольку во всех подграфиках используются одни и те же два теста, я использую легенду на рисунке, а не в подграфиках.
Ядро кода, вероятно, когда-то копировалось из Интернета и изменялось несколько раз, но работает нормально. Однако иногда возникают проблемы с легендами.
Легенда добавляется с помощью fig.legend.

Код: Выделить всё

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math

paths = ['Testdata1.xlsx', 'Testdata2.xlsx']
Sheets = [['List1'],['List2']]

# define the labels of the plot
Labels = ['Dataset1','Dataset2']
Stil =      ['ro-',     'ks-' ]

# define the x-axis parameter, label and range
x_axis ="P_EFF_ME" # Normname  Samme x-akse alle plot
x_axis_label = "x-axes title"

# define the parameters to plot
ParamTitles =   ["A-heading",              "B-heading"   ,    "C-heading"    ,          "D-heading"             ] # Plot heading
ParamLabels =   ["A"             ,        " B",               " C",                     " D"                    ] # Y-axis text
ParamSelect =   ["A_data",                "B_data"    ,       "C_data"  ,               "D_data"                ] # Parametername

# calculate the number of rows and columns for the subplots
num_plots = len(ParamSelect) # number of plots is the same as numbers of elements in ParamSelect
num_cols = min(num_plots, 2) # number of columns is defined as the smallest of either num_plots or 2. If num_plots = 3, then num_cols will still be 2.
num_rows = math.ceil(num_plots / num_cols) # number of rows is found by rounding up num_plots/num_cols. If num_plots = 5 and num_cols = 2, then num_plots/num_cols = 2,5. math.ceil rounds up to 3.

fig, axs = plt.subplots(num_rows, num_cols, figsize=(9, 3 * num_rows))#,layout='constrained')
fig.subplots_adjust(hspace=0.5,wspace=0.3,top=0.9,bottom=0.075) # adjusts margins

for k, path in enumerate(paths):
for j, sheet in enumerate(Sheets[k]):
# read in the data for the current sheet and arranges it as desired for further plotting
df = pd.read_excel(path, sheet_name=sheet).T
df.index=np.arange(0,df.shape[0],1)
df.drop([0,2,3], axis=0,inplace=True)
df.columns=df.iloc[0,:]
df.index=np.arange(0,df.shape[0],1)
df.drop([0], axis=0,inplace=True)

for i, parameter in enumerate(ParamSelect):
# determine the row and column index for the subplot
row = i // num_cols
col = i % num_cols
# plot the data on the appropriate subplot and add a title
axs[row, col].plot(df[x_axis], df[parameter],Stil[k])
axs[row, col].set_xlabel(x_axis_label)
axs[row, col].set_ylabel(ParamLabels[i])
axs[row, col].set_title(ParamTitles[i]) # add title

fig.legend(labels=Labels, loc='outside upper center', bbox_to_anchor=(0.5, 1), ncol=len(Labels), frameon=False)

plt.show()
Обычной и правильной легендой для этого в верхней части рисунка является Dataset1 с красной линией и круглым маркером, а Dataset2 — с черной линией и квадратным маркером.
Однако иногда Dataset2 отображается с красной линией и круглыми кружками.
Я пытался извлечь маркеры из осей, но он возвращает пустые значения.

Код: Выделить всё

handles, labels = axs[row, col].get_legend_handles_labels()
Есть ли способ убедиться, что легенда отображается правильно?
Изображение

Изображение

Изображение

Изображение

Вернуться в «Python»