【问题标题】:Pandas plot: using datafram columns as two-levels x-axis Minor and major tick-lables熊猫图:使用数据框列作为两级 x 轴次要和主要刻度标签
【发布时间】:2022-01-01 15:36:49
【问题描述】:

这是我用来生成下面条形图的数据和代码:

import pandas as pd
import matplotlib.pyplot as plt

data = [["2019","Jan.", 2000,2200,-200],
        ["2019","Feb.", 1500,1400,100],
        ["2019","Dec.", 1200,1100,100],
        ["2020","Jan.", 1400,1300,100],
        ["2020","Dec.", 1300,1200,100]]

df = pd.DataFrame(data, columns=["Year", "Month", "incomes", "expenses", "Balance"])
df.plot.bar()
plt.show()

不过,我想使用 df["Year"] 作为主要刻度标签,使用 df["Month"] 作为次要标签,而不是序号。

这是怎么做到的?

【问题讨论】:

    标签: python-3.x pandas matplotlib


    【解决方案1】:

    您可以通过遍历数据框来创建标签,通过连接年份和月份来创建字符串。

    import pandas as pd
    import matplotlib.pyplot as plt
    
    data = [["2019", "Jan.", 2000, 2200, -200],
            ["2019", "Feb.", 1500, 1400, 100],
            ["2019", "Dec.", 1200, 1100, 100],
            ["2020", "Jan.", 1400, 1300, 100],
            ["2020", "Dec.", 1300, 1200, 100]]
    df = pd.DataFrame(data, columns=["Year", "Month", "incomes", "expenses", "Balance"])
    ax = df.plot.bar()
    ax.set_xticks(range(len(df)))
    ax.set_xticklabels([f"{month}\n{year}" for year, month in zip(df["Year"], df["Month"])], rotation=0)
    plt.show()
    

    【讨论】:

    • 你可能想在y=0添加一行:ax.axhline(0, color='black')
    猜你喜欢
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2015-11-21
    • 2020-10-03
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多