John Munns
John Munns

Reputation: 15

Colors not displaying properly matplotlib bar chart

I am trying to create a bar chart with one colour per bar. Dataset: Dataset Link

When I use the color parameter in a matplotlib bar chart, the colours do not assign one to each bar. They randomly distribute throughout all the bars, with no explicit pattern.

This is the code:

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

#Read file
df = pd.read_excel('CAR DETAILS FROM CAR DEKHO.xlsx')

#Change price column
df["price_sterling"] = df["selling_price"].apply(lambda x: x*0.011)

#PLOT BAR
plt.bar(df.owner,df.price_sterling,color=['red', 'yellow', 'black', 'blue', 'orange'])
plt.xticks(rotation="vertical")
plt.show()

Bar chart output

I don't know what I'm doing wrong. Any ideas?

I have not seen this problem in any of the many tutorials and SO pages I have visited...

Upvotes: 0

Views: 810

Answers (1)

trandangtrungduc
trandangtrungduc

Reputation: 335

Because it will depict the value of your df.price and df.owner in color randomly. I don't know what you're plotting to represent but what if you need to assign a color to each bar. Simply use .set_color for each bar as below example

 graph = plt.bar([1,2,3,4], [10,11,12,13])
 graph[0].set_color('red')
 graph[1].set_color('green')
 graph[2].set_color('orange')
 graph[3].set_color('blue')
 plt.show()

or another way

a = [1, 2, 3, 4]
b = [10, 11, 12, 13]
figure, axes = plt.subplots()
axes.bar(a, b, color=['red', 'green', 'orange', 'blue'])

I think you are trying to calculate the total "selling price" of the "owner"? If so then you can add the following

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

#Read file
df = pd.read_excel('CAR DETAILS FROM CAR DEKHO.xlsx')

#Change price column
df["price_sterling"] = df["selling_price"].apply(lambda x: x*0.011)
new_df = df.groupby(['owner']).sum()

#PLOT BAR
plt.bar(new_df.index,new_df.price_sterling,color=['red', 'yellow', 'black', 'blue', 'orange'])
plt.xticks(rotation="vertical")
plt.show()

Upvotes: 1

Related Questions