我嘗試將具有某些顏色的條形圖繪制到標簽上,并為每種型別制作帶有顏色的圖例。例如,標簽“Type 1”、“Type 2”和“Type 3”每種顏色對應每個標簽。謝謝!
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()
uj5u.com熱心網友回復:
您可以為標簽添加一個額外的列,并使用 seaborn 創建繪圖:
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()

另一種方法,沒有 seaborn,創建兩列:一列用于標簽,一列用于數字索引。最近的 matplotlib 版本接受data=關鍵字,以指示資料框(或資料框的子集)。需要一個數字索引才能在正確的位置繪制條形圖。
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433212.html
標籤:Python matplotlib 阴谋
