带有多索引熊猫数据框的条形图

时间:2021-06-12 05:48:58

标签: pandas dataframe matplotlib multi-index

有没有办法绘制“client_nr”与“Credit Total”的关系图:

示例:

enter image description here

当前代码:

credit_clients.iloc[-1].plot.bar()

产生:

Example 2

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

  • 具有与您的数据框相似的合成数据
  • 绘图很简单,只需要使用 .loc[]
  • 从索引中选择 Client Total
import numpy as np
import pandas as pd

# synthesize data
i = pd.MultiIndex.from_product([pd.date_range("1-jan-2018", freq="M", periods=6), range(10)], names=["yearmonth","client_nr"])
df = pd.DataFrame(index=i, data=np.random.uniform(1,10, len(i))).unstack()
df.columns = df.columns.droplevel(0)
df.loc["Client Total"] = df.sum(axis=0)

# plot it...
df.loc["Client Total"].plot(kind="bar")

数据

<头>
年月 0 1 2 3 4 5 6 7 8 9
2018-01-31 00:00:00 8.48257 9.38166 9.14367 7.52485 8.25407 4.9672 8.28687 2.96698 9.37681 2.36876
2018-02-28 00:00:00 5.99324 8.72813 6.06575 4.19694 8.03992 2.22363 9.56064 8.23965 6.97355 5.8883
2018-03-31 00:00:00 8.85086 8.48972 9.11997 7.91605 6.38338 9.33158 7.26467 8.00862 8.38145 6.81128
2018-04-30 00:00:00 7.69246 5.17472 7.73813 2.75313 7.12725 9.86623 2.16481 8.15056 6.81378 9.01334
2018-05-31 00:00:00 6.05941 3.29547 7.05862 9.83301 4.51411 4.11672 7.53534 5.52747 8.34065 3.13277
2018-06-30 00:00:00 9.7033 9.36859 4.35592 4.4328 5.61218 1.13454 9.63189 3.44345 6.60661 4.43206
客户总数 46.7818 44.4383 43.4821 36.6568 39.9309 31.6399 44.4442 36.3367 46.4928 31.6465

绘图

enter image description here

由 client_nr 着色的条形 - 使用 plotly

import plotly.express as px
px.bar(df.loc["Client Total"].reset_index(), x="client_nr", y="Client Total", color="client_nr")

enter image description here