Pandas bar plot color by column

Pandas Bar Plot – Color by Column

To create a bar plot in Pandas and color the bars based on the values of a specific column, you can use the `plot.bar()` method and pass the `color` parameter with the name of the column you want to use for coloring.

Example

Let’s assume you have a DataFrame named `df` with the following data:

import pandas as pd

data = {'Category': ['A', 'B', 'C', 'D'],
        'Value': [10, 15, 7, 12],
        'Color': ['red', 'blue', 'green', 'yellow']}

df = pd.DataFrame(data)

This DataFrame has three columns: `Category`, `Value`, and `Color`. You want to plot a bar chart where bars are colored based on the `Color` column.

Here is how you can achieve this:

import matplotlib.pyplot as plt

df.plot.bar(x='Category', y='Value', color='Color')
plt.show()

In this example, we specify the `x` and `y` parameters as `’Category’` and `’Value’` respectively, to determine the data for the x-axis and y-axis. The `color` parameter is set to `’Color’` to indicate that the bars should be colored based on the values in the `Color` column of the DataFrame.

When you run this code, you will get a bar plot with bars colored according to the values in the `Color` column.

Leave a comment