Multiple columns of df show as 1 single label in legend and show how many columns are representing on matplotlib

I have a dataframe that contains temperature of 3 meteorological networks and each ones contains a certain meteorological stations, so the columns 0 to 34 are stations of ‘REDMET’ meteorological network, the next 15 colums are stations of ‘PEMBU’ meteorological network and the last 4 columns are stations of ‘RUOA’ meteorological network and my index are dates

I plot a diferent ranges of dates but in the legend i want to show how many stations of each meteorological networks are ploting
For example in the first plot, only 30 stations of ‘REDMET’ have data, 13 stations of ‘PEMBU’ and 4 of ‘RUOA’, so the leyend have to say

REDMET (30) 
PEMBU (13)
RUOA (4)
Estaciones_data = pd.read_csv(ruta, header=0, na_values=["-99"], index_col="Fecha_hora")
Estaciones_data.index = pd.to_datetime(Estaciones_data.index)

filtro_fechas = (Estaciones_data.index >= '2020-01-01') & (Estaciones_data.index < '2023-07-01')

Estaciones_data = Estaciones_data[filtro_fechas]

colores = ['deepskyblue'] * 35 + ['indigo'] * 15 + ['tab:red'] * 4
linestyle=['-'] * 35 + ['-.'] * 15 + ['--'] * 4

rangos_fechas = [
('2020-01-01', '2020-01-31'),
('2021-04-01', '2021-04-30'),
('2022-03-01', '2022-03-31'),
('2022-04-01', '2022-04-30'),
('2023-04-01', '2023-04-30'),
('2023-06-01', '2023-06-30'),
('2020-06-01', '2020-06-30'),
('2022-05-01', '2022-05-31'),
('2023-01-01', '2023-01-31'),
('2023-03-01', '2023-03-31'),
('2023-05-01', '2023-05-31')
]

for i, (inicio, fin) in enumerate(rangos_fechas, start=1):
    plt.figure(figsize=(12, 6))
    
    datos_rango = Estaciones_data[(Estaciones_data.index >= inicio) & (Estaciones_data.index <= fin)]
    
    legend_labels = []
    legend_lines = []
    
    count_redmet = 0
    count_pembu = 0
    count_ruoa = 0

    for j, (col, color, ls) in enumerate(zip(Estaciones_data.columns, colores, linestyle)):
        line, = plt.plot(datos_rango[col], color=color, linestyle=ls, linewidth=2)
        
        if j < 35 and datos_rango[col].notna().any():
            count_redmet += 1
        elif 35 <= j < 50 and datos_rango[col].notna().any():
            count_pembu += 1
        elif j >= 50 and datos_rango[col].notna().any():
            count_ruoa += 1
        
        if datos_rango[col].notna().any():
            legend_labels.append(f'{col}')
            legend_lines.append(line)
    
    legend_labels.append(f'REDMET ({count_redmet})')
    legend_labels.append(f'PEMBU ({count_pembu})')
    legend_labels.append(f'RUOA ({count_ruoa})')
    
    plt.legend(handles=legend_lines, labels=legend_labels, loc="upper right")
    
    x_dates = pd.date_range(start=inicio, end=fin, freq='5D')
    x_labels = [date.strftime('%d/%m') for date in x_dates]
    plt.xticks([]) 
    plt.xticks(x_dates, x_labels)  
    
    plt.title(f'{inicio} al {fin}')
    plt.xlabel('Fecha')
    plt.ylabel('Temperatura del aire $[°C]$')
        
    plt.show()

Leave a Comment