AnnaP
AnnaP

Reputation: 15

How to make DataFrame plot bars be shown in different colors?

I am a newbie data analyst and I am trying to create a dataframe bar chart with df.plot() so that the bars have different colors. I found out that there are no arguments that can be passed to color the bars in different colors unless the dataframe is transposed. I tried to transpose it with the below code:

gender_overview = pd.read_sql("SELECT Gender, COUNT(*) AS NumberOfPeople "
                          "FROM [AdventureWorks2019].[Sales].[vPersonDemographics] "
                          "GROUP BY Gender "
                          "ORDER BY NumberOfPeople DESC;", conn)

display(gender_overview)
df = gender_overview.set_index('Gender')
ax = df.T.plot(kind='bar', label='index', colormap='Paired')
labels = ['Male', 'Female', 'Not Specified']
ax.set_xticks(range(len(df)))
ax.set_xticklabels(labels=labels, rotation=0)
plt.show()

however, the bars and x_ticks ended up to be mismatched (please see the screenshot here.)

How can I make sure that bars match with the respective x_ticks?

Thank you in advance for your help :)

Upvotes: 0

Views: 1152

Answers (1)

wbg
wbg

Reputation: 928

I find that I cannot use Pandas for plotting when I want some fine control. I tend to lean on matplotlib.

import panda as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame()
df['test'] = np.arange(6)
df['gender'] = ['M', 'F', 'F', 'M', 'F', 'F']
df.set_index('gender', inplace=True)

plt.bar(df.index, df['test'], color=['blue', 'red'])
plt.show()

It's tempting to try the group-by, but I don't think it helps.

g = df.groupby("gender").count()
plt.bar(g.index, g['test'], color=['blue', 'red'])
plt.show()

Upvotes: 1

Related Questions