Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot multiple pandas columns

Tags:

I have dataframe total_year, which contains three columns (year, action, comedy) .

total_year

enter image description here

I want to plot the year column on the x-axis, and action & comedy both on the y-axis.

How can I plot two columns (action and comedy) on y-axis?

My code plots only one column on y-axis.

total_year[-15:].plot(x='year', y='action', figsize=(10,5), grid=True)

enter image description here

like image 344
Bilal Butt Avatar asked Dec 12 '17 14:12

Bilal Butt


People also ask

How do I plot multiple columns in pandas?

Pandas has a tight integration with Matplotlib. You can plot data directly from your DataFrame using the plot() method. To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function.

How do I plot specific columns in pandas?

To plot a specific column, use the selection method of the subset data tutorial in combination with the plot() method. Hence, the plot() method works on both Series and DataFrame .

How do I make a two column bar graph in Python?

Matplotlib bar chart multiple columns We use the plot() method to draw a bar chart and to define multiple columns, we use the DataFrame object. Example: Here we are going to create multiple bar charts by using the DataFrame object of Pandas.


2 Answers

Several column names may be provided to the y argument of the pandas plotting function. Those should be specified in a list, as follows.

df.plot(x="year", y=["action", "comedy"])

Complete example:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"year": [1914,1915,1916,1919,1920],
                   "action" : [2.6,3.4,3.25,2.8,1.75],
                   "comedy" : [2.5,2.9,3.0,3.3,3.4] })
df.plot(x="year", y=["action", "comedy"])
plt.show()

enter image description here

like image 86
ImportanceOfBeingErnest Avatar answered Sep 20 '22 16:09

ImportanceOfBeingErnest


Pandas.DataFrame.plot() per default uses index for plotting X axis, all other numeric columns will be used as Y values.

So setting year column as index will do the trick:

total_year.set_index('year').plot(figsize=(10,5), grid=True)
like image 39
MaxU - stop WAR against UA Avatar answered Sep 24 '22 16:09

MaxU - stop WAR against UA