0

I try to plot a bar graph with certain colors to labels and make legend with color for each type. For example, labels "Type 1", "Type 2" and "Type 3" each color corresponding to each label. Thanks!

import matplotlib.pyplot as plt
import pandas as pd
mdict={"Types":["A","B","C","D","F", "G"],"Count":[3,4,5,6,7,6]}
df=pd.DataFrame(mdict)

fig, ax=plt.subplots(figsize=(15,8))

for i in df.Types:
    if i in ["A","B"]:
        ax.bar(df.Types,df.Count,color="red", label="Type 1")
    elif i in ["C","D"]:
        ax.bar(df.Types,df.Count,color="green", label="Type 2")
    else:
        ax.bar(df.Types,df.Count, color="blue", label="Type 3")
ax.legend()

1 Answer 1

2

You could add an extra column for the labels, and use seaborn to create the plot:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

mdict = {"Types": ["A", "B", "C", "D", "F", "G"], "Count": [3, 4, 5, 6, 7, 6]}
df = pd.DataFrame(mdict)

df["Label"] = "Type 3"
df.loc[df["Types"].isin(["A", "B"]), "Label"] = "Type 1"
df.loc[df["Types"].isin(["C", "D"]), "Label"] = "Type 2"

fig, ax = plt.subplots(figsize=(15, 8))
palette = {"Type 1": "crimson", "Type 2": "limegreen", "Type 3": "dodgerblue"}
sns.barplot(data=df, x="Types", y="Count", hue="Label", palette=palette, dodge=False, ax=ax)
plt.show()

sns.barplot colored via type

An alternative approach, without seaborn, creates two columns: one for labels and one for a numeric index. Recent matplotlib versions accept a data= keyword, to indicate a dataframe (or a subset of a dataframe). A numeric index is needed to draw the bars at the correct positions.

import matplotlib.pyplot as plt
import pandas as pd

mdict = {"Types": ["A", "B", "C", "D", "F", "G"], "Count": [3, 4, 5, 6, 7, 6]}
df = pd.DataFrame(mdict)

df["Label"] = ["Type 1" if i in ["A", "B"] else "Type 2" if i in ["C", "D"] else "Type 3" for i in df["Types"]]
df["ind"] = range(len(df))

fig, ax = plt.subplots(figsize=(15, 8))
ax.bar("ind", "Count", color="crimson", label="Type 1",
       data=df.loc[df["Types"].isin(["A", "B"])])
ax.bar("ind", "Count", color="limegreen", label="Type 2",
       data=df.loc[df["Types"].isin(["C", "D"])])
ax.bar("ind", "Count", color="dodgerblue", label="Type 2",
       data=df.loc[~ (df["Types"].isin(["A", "B"]) | df["Types"].isin(["C", "D"]))])
ax.set_xticks(df["ind"], df["Types"])
ax.legend()
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.