[英]Change stacked bar plot legend in Python
我在csv文件中包含以下數據:
Date City TruckA TruckB TruckC TruckD
Date1 City1 1 0 0 0
Date1 City2 0 0 1 0
Date1 City3 1 0 0 0
Date1 City4 0 0 1 0
Date2 City1 1 0 0 0
Date2 City2 0 1 0 0
Date2 City3 0 0 0 1
Date2 City4 1 0 0 0
Date2 City5 0 1 0 0
Date3 City1 1 0 0 0
Date3 City2 0 0 1 0
Date3 City3 1 0 0 0
Date3 City4 0 0 1 0
我可以使用以下代碼成功繪制數據:
import pandas as pd
df = pd.read_csv("data.csv")
print(df)
df = df.set_index(["Date","City"])
df.unstack().plot(kind='bar', stacked=True)
我得到以下結果:
如您所見,顏色圖例就像每對(城市,卡車)都有顏色。 我希望圖例僅依賴於卡車,並且理想情況下在每個城市的條形圖上都有標簽。
這可能嗎?
遵循@Scott的絕佳回答,您可以根據需要獲取堆疊的列。
import matplotlib.pyplot as plt
cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
df_out = df.unstack()
d = dict(zip(df.columns.get_level_values(0),cycle))
c = df_out.columns.get_level_values(0).map(d)
g=df_out.plot.bar(stacked=True, color=c, figsize=(10,8), edgecolor='k')
要添加標簽,您需要找到正確的位置並反復進行標簽。
這是一種實現方法:
h=0
x=0
unique_dates=df1.index.get_level_values(0).unique() # get the bars
city=df_out.iloc[x][df_out.iloc[x]!=0].dropna().index.get_level_values(1) #get the cities
for y,val in enumerate(df1.index.get_level_values(0)): #loop through the dates
if val==unique_dates[x]: #check the x position
g.text(x-0.05,1+h-0.5,"%s" % city[h])
h+=1
else: # move to next x coord, update city labels and add text for the next x coordinate (h=0)
x+=1
city=df_out.iloc[x][df_out.iloc[x]!=0].dropna().index.get_level_values(1) #get cities
g.text(x-0.05,1-0.5,"%s" % city[0])
h=1 # set h to 1 as we already printed for h=0
原始解決方案
for x ,date in enumerate(df_out.index):
h=0
city=df_out.iloc[x][df_out.iloc[x]!=0].dropna().index.get_level_values(1) #get cities
for y,val in enumerate(df.index.get_level_values(0)):
if val==date:
g.text(x,1+h-0.5,"%s" % city[h])
h+=1
else:
continue
import matplotlib.pyplot as plt
cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
df_out = df.unstack()
d = dict(zip(df.columns.get_level_values(0),cycle))
c = df_out.columns.get_level_values(0).map(d)
df_out.plot.bar(stacked=True, color=c, figsize=(10,8))
輸出:
添加了edgecolor以區分城市:
import matplotlib.pyplot as plt
cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']
df_out = df.unstack()
d = dict(zip(df.columns.get_level_values(0),cycle))
c = df_out.columns.get_level_values(0).map(d)
df_out.plot.bar(stacked=True, color=c, figsize=(10,8), edgecolor='k')
IIUC,我認為您正在尋找這樣的東西:
df = df.set_index(["Date","City"])
df.sum(level=0).plot.bar(stacked=True, figsize=(10,8))
輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.