使用matplotlib绘制2级xtick标签,如excel

现在我有一个这样的数据框:

| category1 | 142 | | | | 166 | | | 186 | | | | |-----------|------|-------|------|------|------|------|------|------|------|------|------| | category2 | 626 | 346 | 211 | 200 | 255 | 250 | 245 | 370 | 340 | 265 | 260 | | y | 0.26 | -0.54 | 2.07 | 3.15 | 0.53 | 0.72 | 2.03 | 0.71 | 0.36 | 1.83 | 0.78 | 

在Excel中,我可以绘制一个带有2个xticklabels类别的标记“line with line”:categrory1和category2。

有什么好的方法来绘制使用python matplotlib类似的情节?

在这里输入图像说明

到目前为止,我只能添加1个xticklabel级别:

 import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("./2level_test.csv", delimiter = ",") column_name = df.columns.values.tolist() print( column_name) df = df.sort_values(by=["category1", "category2"], ascending=[True, True]) numRows = len(df.index) index = range(1, numRows+1, 1) y = df["y"].values.tolist() fig = plt.figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], label="ax") ax.plot(index, y, linestyle='--', color = 'g', marker= '^', markeredgewidth = 1, markeredgecolor='r', markerfacecolor='none', label='y') # title and lables ax.set_xticks(index) category2 = df["category2"].values.tolist() ax.set_xticklabels(category2, rotation=270) ax.set_ylabel("y") ax.set_xlabel("category2") plt.show() 

在这里输入图像说明

感谢James的提醒,使用pandas的情节,我可以将2个类别合并成1个xtick标签,但仍然不完全符合我的要求。

 import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("./2level_test.csv", delimiter = ",") df = df.sort_values(by=["category1", "category2"], ascending=[True, True]) df.plot(x=['category1', 'category2'], y='y', linestyle='--', color = 'g', marker= '^', markeredgewidth = 1, markeredgecolor='r', markerfacecolor='none', label='y') plt.show() 

在这里输入图像说明