繁体   English   中英

在 matplotlib 中使用条形图更改某些条形标签的颜色

[英]Change color at certain bar labels with barplot in matplotlib

我尝试将 plot 带有某些 colors 的条形图添加到标签中,并为每种类型制作带有颜色的图例。 例如标签“Type 1”、“Type 2”和“Type 3”每种颜色分别对应label。谢谢!

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()

您可以为标签添加一个额外的列,并使用 seaborn 创建 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 通过类型着色

另一种方法没有 seaborn,它创建两列:一列用于标签,一列用于数字索引。 最近的 matplotlib 版本接受data=关键字,以指示 dataframe(或数据帧的子集)。 需要一个数字索引来在正确的位置绘制条形图。

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM