Python – Draw a line chart (multiple lines) from a Pandas data frame

Draw a line chart (multiple lines) from a Pandas data frame… here is a solution to the problem.

Draw a line chart (multiple lines) from a Pandas data frame

I’m currently working on the following data frame.


To summarize the content, there is an “Age” column, which is related to the age group (i.e. 16-25, 26-32) – then 8 class percentage values, these are percentage values that tell me how many percentages of people of a certain age belong to that particular social class. So in this example, 10.81% (rounded) of the age group with ID 1 are also in the social class with ID 1. For the same age group, 22.34% of social classes have an ID of 2, and so on. Each row adds up to 100%.

I want to create a line chart with a line representing each age group. So this graph should have a total of 5 lines.


x-axis should represent the social class (from 1 to 8), and the y-axis should represent the percentage of the population for that class.

I’m looking for charts in this format to get a clear picture of the number patterns for each different age group, each social class, and how this changes with age.


would appreciate any help, I’m not even sure where to start? I’ve tried some examples online but nothing seems to work. Even the appetizers were great.

Thank you.


You can do it in two lines. First, you can simply pivot your dataset so that it is in the shape you want to draw:

df_plot = df.set_index('age'). T

This results in (the numbers are randomly generated and are different from the numbers you provided):

age          1       2       3       4       5
class1  0.5377  0.2147  0.4837  0.8682  0.3429
class2  0.8350  0.0544  0.4314  0.6592  0.6475
class3  0.9382  0.0283  0.7152  0.0962  0.3012
class4  0.7277  0.1523  0.3124  0.0077  0.4039
class5  0.7580  0.4149  0.1352  0.5068  0.2955
class6  0.3243  0.3346  0.2820  0.8481  0.9782
class7  0.2298  0.0522  0.7307  0.9851  0.8681
class8  0.3283  0.0562  0.9052  0.6320  0.6140

Then generate a plot by calling the built-in plotting function:

df_plot.plot(figsize=(10,6), xticks=range(0, 8)).legend(title='age', bbox_to_anchor=(1, 1))

This results in:
enter image description here

Related Problems and Solutions