user234568
user234568

Reputation: 815

Plot graph with the data showing respective colors

color = []
for key,value in ms.iterrows():
    if(value['Color']=='Blue'):
       color.append('b')
    elif(value['Color']=='Green'):
       color.append('g')
    elif(value['Color']=='Red'):
       color.append('r')
    elif(value['Color']=='Yellow'):
       color.append('y')
    elif(value['Color']=='Orange'):
       color.append('o')
    else:
       color.append('k')
ax =ms[['Height','Color']].plot(x='Color', kind='bar', title="Correlation", 
figsize=(15,10), color=color legend=True, fontsize=12)
ax.set_xlabel("Colors", fontsize=12)
ax.set_ylabel("Height", fontsize=12)

Data

Graph

My intention is to plot a bar graph that shows Color against Height. I managed to do it. However, I would like each of the bars to show respective color. In accord with the data set, I would like the 1st bar to show red...and so on. I tried adding the color, but it still shows only 1 color.

Upvotes: 2

Views: 138

Answers (2)

BhishanPoudel
BhishanPoudel

Reputation: 17154

You do not have to create if/else conditions:

import pandas as pd
df = pd.DataFrame({"Height" : [5,3,6,4],
                   "Color" : ["Blue", "Green", "Red", "Yellow"]})

df.set_index('Color').Height.plot(kind='bar',color=df.Color)

enter image description here

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339230

The trick is to create a multicolumn dataframe and use the stacked=True option.

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

df = pd.DataFrame({"Height" : [5,3,6,4],
                   "Color" : ["Blue", "Green", "Red", "Yellow"]})

color = []
for key,value in df.iterrows():
    if(value['Color']=='Blue'):
       color.append('b')
    elif(value['Color']=='Green'):
       color.append('g')
    elif(value['Color']=='Red'):
       color.append('r')
    elif(value['Color']=='Yellow'):
       color.append('y')
    elif(value['Color']=='Orange'):
       color.append('o')
    else:
       color.append('k')

df2 = pd.DataFrame(np.diag(df["Height"]), columns=df["Color"], index=df["Color"])
ax = df2.plot(kind='bar', title="Correlation", color=color, legend=True, 
              fontsize=12, stacked=True)
ax.set_xlabel("Colors", fontsize=12)
ax.set_ylabel("Height", fontsize=12)

plt.show()

enter image description here

Upvotes: 2

Related Questions