📜  Python| Pandas Dataframe.plot.bar(1)

📅  最后修改于: 2023-12-03 14:46:22.600000             🧑  作者: Mango

Python | Pandas Dataframe.plot.bar

Pandas is one of the most widely used Python libraries for data manipulation and analysis. It has many functionalities including visualization options for better understanding of the data. In this tutorial, we will discuss Pandas Dataframe.plot.bar function which helps in creating bar charts.

What are bar charts?

A bar chart is a type of chart that represents categorical data with rectangular bars. Each bar represents a category and the height of the bar corresponds to the value of that category.

Pandas Dataframe.plot.bar function

The Pandas Dataframe.plot.bar() function is used to create vertical bar charts. We can pass various parameters to this function to customize our bar chart including bar width, color, title, and more.

Syntax

The syntax for Pandas Dataframe.plot.bar() function is:

DataFrame.plot.bar(x=None, y=None, **kwargs)
Parameters
  • x: Label or position of the x-axis.
  • y: Label or position of the y-axis.
  • **kwargs: Keyword arguments that are passed to the plotting method. Some of the frequently used kwargs are:
    • figsize: Size of the figure (tuple).
    • color: Color of the bars.
    • alpha: Transparency of the bars.
    • title: Title of the chart.
    • xlabel: Label of the x-axis.
    • ylabel: Label of the y-axis.
Example
import pandas as pd

# Create a Pandas dataframe
df = pd.DataFrame({
    'Country': ['United States', 'Russia', 'China', 'Germany', 'United Kingdom'],
    'GDP': [19.39, 4.0, 14.14, 4.17, 2.62]
})

# Set the index of the dataframe to the Country column
df = df.set_index('Country')

# Create a bar chart using Pandas Dataframe.plot.bar() function
df.plot.bar(figsize=(8, 6), color='b', alpha=0.75, rot=0, title='GDP of Top 5 Countries (in trillions USD)')

# Set the label of the x-axis and y-axis
plt.xlabel('Country')
plt.ylabel('GDP (trillions USD)')

# Show the chart
plt.show()

This will create a vertical bar chart of the GDP of the top 5 countries in trillions USD.

Conclusion

In this tutorial, we discussed Pandas Dataframe.plot.bar() function which is used to create vertical bar charts. We also discussed the syntax and parameters of this function along with an example. Pandas Dataframe.plot.bar() function is a useful tool for visualizing categorical data in a clear and concise manner.