Coding Ref

How to create a bar chart in Pandas

How to create a bar chart in Pandas

To create a bar chart in Pandas, you can use the DataFrame.plot.bar() method.

Here's an example:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})

# create a bar chart
df.plot.bar()

This will create a basic vertical bar chart with the columns of the dataframe as the categories on the x-axis and the corresponding values as the bar heights.

Horizontal bar chart

If you want to create a horizontal bar chart, use df.plot.barh().

For example:

main.py
# create a horizontal bar chart
df.plot.barh()

Customizing the bar chat

You can also customize various aspects of the bar chart, such as the colors, width, and spacing, by passing additional parameters to the plot.bar() method. For example:

main.py
# create a bar chart with custom colors and width
df.plot.bar(color=['C0', 'C4'], width=0.8)

This will create a bar chart with the colors specified in the color parameter and the widths specified in the width parameter.

You can also create a stacked bar chart by setting the stacked parameter to True. For example:

main.py
# create a stacked bar chart
df.plot.bar(stacked=True)

This will create a stacked bar chart with the columns of the dataframe as the categories on the x-axis and the corresponding values as the bar heights.

Saving the bar chart

Finally, you can save the bar chart to a file by calling the savefig() method on the plot object, like this:

main.py
# create a bar chart
ax = df.plot.bar()

# save the bar chart to a file
ax.figure.savefig("bar_chart.png")

This will save the bar chart as a PNG file with the specified file name.

You can also specify the file format by changing the file extension in the file name (e.g. "bar_chart.pdf" for a PDF file).

You'll also like

Related tutorials curated for you

    How to calculate the variance in Pandas DataFrame

    How to apply a function to multiple columns in Pandas

    How to use where() in Pandas

    How to use astype() in Pandas

    How to concatenate in Pandas

    How to normalize a column in Pandas

    How to sort a series in Pandas

    How to use qcut() in Pandas

    What is Pandas Cumsum()?

    How to create a bar chart in Pandas

    How to convert Pandas timestamp to datetime

    How to reshape a Pandas DataFrame