Giri
Giri

Reputation: 55

How to do line plot for each column separately based on another column for each two samples for pandas dataframe?

I have dataframe as ,

i need something like this for each columns like stress , depression and anxiety and each participant data in each category

samople out that i needed

i wrote the python code as

ax = data_full.plot(x="participants", y=["Stress","Depression","Anxiety"],kind="line", lw=3, ls='--', figsize = (12,6)) 
plt.grid(True)
plt.show()

get the output like this

my script output

Upvotes: 0

Views: 1062

Answers (1)

r-beginners
r-beginners

Reputation: 35135

Split the participant column and merge it with the original data frame. Change the data frame to a data frame with only the columns you need in the merged data frame. Transform the data frame in its final form by pivoting. The resulting data frame is then used as the basis for the graph. Now we can adjust the x-axis tick marks, the legend position, and the y-axis limits.

dfs = pd.concat([df,df['participants'].str.split('_', expand=True)],axis=1)
dfs.columns = ['Stress', 'Depression', 'Anxiety', 'participants', 'category', 'group']
fin_df = dfs[['category','group','Stress']]
fin_df = dfs.pivot(index='category', columns='group', values='Stress')
# update
fin_df = fin_df.sort_index(ascending=False)
g = fin_df.plot(kind='line', title='Stress')
g.set_xticks([0,1])
g.set_xticklabels(['pre','post'])
g.legend(loc='center right')
g.set_ylim(5,25)

enter image description here

Upvotes: 3

Related Questions