在Python中更改堆积条形图图例

2024-09-29 02:22:11 发布

您现在位置: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

我可以用以下代码成功绘制数据:

^{pr2}$

我得到以下结果: Image

正如你所看到的,颜色的传奇是这样的每一对(城市,卡车)有一个颜色。我希望传奇只依赖于卡车,理想的是每个城市的条形图上都有标签。在

这可能吗?在


Tags: 文件csv数据citydate颜色传奇卡车
2条回答

按照@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')

要添加标签,您需要找到正确的位置并迭代地添加标签。
以下是一种方法:

编辑:仅一个循环

^{pr2}$

原液

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

image

编辑

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

输出:

enter image description here

添加了edgecolor以区分城市:

^{pr2}$

enter image description here


IIUC,我想你在找这样的东西:

df = df.set_index(["Date","City"])
df.sum(level=0).plot.bar(stacked=True, figsize=(10,8))

输出:

enter image description here

相关问题 更多 >