patternpythonMinor
Plotting from a Pandas dataframe
Viewed 0 times
plottingfromdataframepandas
Problem
I want to improve my code. Is it possible to get the plot without repeating the same instructions multiple lines?
The data comes from a Pandas' dataframe, but I am only plotting the last column (Total Acc.)
The data comes from a Pandas' dataframe, but I am only plotting the last column (Total Acc.)
e=df['Total Acc'].round(4)*100
#The repetitions start:
row_awa = e.loc['AWA']
row_rem = e.loc['REM']
row_s1 = e.loc['S1']
row_s2 = e.loc['S2']
row_sws = e.loc['SWS']
row_stades = e.loc['stades']
#More repetitions
row_awa.plot()
row_rem.plot()
row_s1.plot()
row_s2.plot()
row_sws.plot()
row_stades.plot()
myLegend=plt.legend(bbox_to_anchor=(0., 1.2, 1., .102), prop ={'size':10}, loc=10, ncol=4, #left, bottom, width, height
title=r'TOTAL ACCURACY FOR MANY K-FOLD') #loc='center'
myLegend.get_title().set_fontsize('20')Solution
To reduce the repetitions you could make use of lists by doing something like:
Edit: The
labels = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'stades']
rows = []
for label in labels:
rows.append(e.loc[label])
# or even shorter with list comprehension
rows = [e.loc[label] for label in labels]
for row in rows:
row.plot()Edit: The
labels list can also be used as first argument of the legend function to show the correct labels.Code Snippets
labels = ['AWA', 'REM', 'S1', 'S2', 'SWS', 'stades']
rows = []
for label in labels:
rows.append(e.loc[label])
# or even shorter with list comprehension
rows = [e.loc[label] for label in labels]
for row in rows:
row.plot()Context
StackExchange Code Review Q#144476, answer score: 3
Revisions (0)
No revisions yet.