简体   繁体   中英

multi-line plotting in Python

So I want to plot a multi-line plot like this: 在此处输入图片说明

Now I am trying to do it myself, but the ethnic groups like White, Black, Asian etc etc are in a column under the heading of "Ethnicity"

This is what my data looks like after filtering from the original dataframe:

plt1_data = df1.loc[(df1.Region == "All") & (df1.Age == "All") & (df1.Sex == "All"),["Ethnicity","Value","Time"]]
                       Ethnicity Value  Time
12                           All   4.8  2004
192                        Asian   9.4  2004
372                  Asian Other   9.3  2004
552                        Black  12.8  2004
732                       Indian   6.9  2004
...                          ...   ...   ...
34212  Pakistani and Bangladeshi   8.4  2018
34392                    Unknown   4.1  2018
34572                      White   3.7  2018
34752              White British   3.8  2018
34932                White Other   3.4  2018

And this is the code that I am using to get a graph similar to one above:

plt.figure(figsize=(20,10))
plt.plot( 'Time', 'Ethnicity', data=plt1_data, color='red')
plt.plot( 'Time', 'Ethnicity', data=plt1_data, color='yellow')
plt.plot( 'Time', 'Ethnicity', data=plt1_data, color='magenta')
plt.plot( 'Time', 'Ethnicity', data=plt1_data, color='blue')
plt.legend()

But it doesnt work well and gives me the following graph: 在此处输入图片说明

So I need help with fixing my graph. Highly appreciate it!

Update graph: 在此处输入图片说明

Code for Update graph:

plt.figure(figsize=(30,30))
for cat, df_cat in plt1_data.groupby('Ethnicity'):
    plt.plot(df_cat['Time'],df_cat['Value'], label=cat)
plt.legend()

Consider using seaborn :

import seaborn as sns

sns.lineplot(data=plt1_data, x='Time', y='Value', hue='Ethnicity')

What you need is to do a "groupby" and to loop over the resulting ethnicities and dataframes

plt.figure(figsize=(20,10))
for cat, df_cat in plt1_data.groupby('Ethnicity'):
    plt.plot(df_cat['Time'],df_cat['Value'], label=cat)
plt.legend()

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