简体   繁体   中英

how to customize the legend in python?

Each CSV file has different n and m values, I want to compare the plots to each other but with this code I am just seeing lines without knowing which plot belong to which CSV. I want to visualize the legend in ( n= "value", m = "value" ) in the code below:

plt.rcParams["figure.figsize"] = [10, 10]
plt.rcParams["figure.autolayout"] = True

columns = ["filename", "filtered","filtered_max","threshold2", "pfa", "m", "n", ]
# setup env
f= Path.cwd().joinpath("/home / ....")
if not f.is_dir():
   f.mkdir()
fh = open('tst_zero.csv', 'w')
cvs_writer = csv.writer(fh)
cvs_writer.writerow(["filename", "count"])                                                                                                 
fh.close()
all_files = glob.glob(f'{f}/results_*.csv')
li = []
color = cm.rainbow(np.linspace(0, 1))
for filename in all_files:
   frame = pd.read_csv(filename, usecols=columns)
   li.append(frame)
   count = (frame['filtered_max'] == 0).groupby(frame['pfa']).sum()
   out2= [filename,count]
   fh = open("tst_zero.csv", 'a')  # `a` for `append mode`
   cvs_writer = csv.writer(fh)
   cvs_writer.writerow(out2)
   fh.close()
   print(filename , 'Count of zeros in filtered_max : ', count)
   plt.title("Pfa vs Threshold ")
   plt.xlabel('Threshold')
   plt.ticklabel_format(axis='y',style='sci',scilimits=(2,10))
   plt.ylabel('Pfa')
   plt.plot(frame.threshold2, frame.pfa)  
plt.grid()
plt.show()

It looks like you already have a column that lists all of their filenames. You could set the label of each plot to the filename and then call plt.legend() for it show all the filenames as the legend labels:

Example:

### Values in the csvs:
_1_10 = [1,2,3,4,5,6,7,8,9,10]
_10_1 = [10,9,8,7,6,5,4,3,2,1]
Mixed = [5,10,3,8,9,6,7,1,2,4]

import pandas as pd
import matplotlib.pyplot as plt
import glob
for example in glob.glob("Example/*.csv"):
    df = pd.read_csv(example)
    filename = example.split('\\')[1]
    plt.plot(df.Value, label=filename)
plt.legend()
plt.show()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM