Python Pandas - Create a Horizontal Bar Chart

PythonServer Side ProgrammingProgramming

To plot a Horizontal Bar Plot, use the pandas.DataFrame.plot.barh. A bar plot shows comparisons among discrete categories.

At first, import the required libraries −

import pandas as pd
import matplotlib.pyplot as plt

Create a Pandas DataFrame with 4 columns −

dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})

Plot Horizontal Bar Chart using the plot.barh() −

dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')

Example

Following is the complete code −

import pandas as pd
import matplotlib.pyplot as plt

# creating dataframe
dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})

# plotting Horizontal Bar Chart
dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')

# set the label
plt.xlabel("CC (Cubic Capacity)" )

# display the plotted Horizontal Bar Chart
plt.show()

Output

This will produce the following output −

raja
Published on 01-Oct-2021 12:39:56
Advertisements