'use different data for legend matplotlib

I'm trying to create a legend that corresponds to other data in dataframe rather than the column used to create the bar plot. My understanding is that matplotlib legend, uses the data input to assign legends, since I enter one column (x) and one column (y) I get one legends only. I'm trying to use the "position "column as my legend input, such that I'll have 3 legends inputs ['bot','mid','top'] with their respective bars assigned. Not sure how.

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

df = pd.DataFrame({'wins': [8,6,2],
                   'player': ['x','y','z'],
                   'position' : ['bot', 'mid', 'top'],
                   'color': ['red', 'blue', 'green']})

bar = plt.bar(df["player"], df["wins"], color = (df["color"]))
bar = plt.legend(labels =df['position'])

results of code



Solution 1:[1]

Using seaborn, one would write this as:

import seaborn as sns

sns.barplot(data=df, x='player', y='wins', hue='position', dodge=False,
            palette=dict(zip(df['position'], df['color'])))

seaborn barplot with hue

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JohanC