Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’,’mid’] 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading