pythondictionarymatplotlibseaborn

Seaborn Code for Plotting Multiple Line Plots


I used read the json file (16_results.json) to read data, I want to creates multiple line plots using the Seaborn and Matplotlib libraries to visualize data for four different values (fed_acc, fed_pre, fed_recall and fed_f1) across 6 values (x).

my code:

import os
import random
from tqdm import tqdm
import pandas as pd
import numpy as np
import torch.nn as nn 
import json
import seaborn as sns
import matplotlib.pyplot as plt

i = 16
# To read the json file
a_file = open(str(i)+"_results.json", "r")
a_dictionary = json.load(a_file)

mp = a_dictionary

print((a_dictionary.keys()))


x = [print(i) for i in range(1,7)]

sns.lineplot(x=x, y=mp['16']['fed_acc'],  marker='o',color='navy', label='acc')

json file (16_results.json)

{"16": {"fed_acc": [0.9981039991573329, 0.9981039991573329, 0.9981039991573329, 0.998139110284049, 0.998139110284049, 0.9983497770443454],
 "fed_pre": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
 "fed_recall": [0.0, 0.0, 0.0, 0.018518518518518517, 0.018518518518518517, 0.12962962962962962],
 "fed_f1": [0.0, 0.0, 0.0, 0.03636363636363636, 0.03636363636363636, 0.22950819672131148]}}

but it doesn't work! it return empty figure!


Solution

  • You can use pd.read_json and some index manipulations:

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    i = 16
    
    df = (pd.read_json(f'{i}_results.json')[i].explode()
            .rename('value').rename_axis('metric').reset_index()
            .assign(epoch=lambda x: x.groupby('metric').cumcount()+1)
            .pivot(index='epoch', columns='metric', values='value'))
    
    ax = sns.lineplot(df)
    plt.show()
    

    Dataframe:

    >>> df
    metric   fed_acc    fed_f1 fed_pre fed_recall
    epoch                                        
    1       0.998104       0.0     0.0        0.0
    2       0.998104       0.0     0.0        0.0
    3       0.998104       0.0     0.0        0.0
    4       0.998139  0.036364     1.0   0.018519
    5       0.998139  0.036364     1.0   0.018519
    6        0.99835  0.229508     1.0    0.12963
    

    Output:

    enter image description here