【发布时间】:2016-02-29 15:41:13
【问题描述】:
现在我有一个这样的数据框:
| 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 绘制“带标记线”图: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()
【问题讨论】:
-
既然您已经在使用 pandas,那么 pandas 绘图功能是否足够?例如,查看第二个示例 here。您应该能够在表格下方传递一系列您想要的值,我认为这更接近您在 Excel 中试图模仿的值。
-
@James,感谢您的提醒,这里是 pandas 的绘图结果:stackoverflow.com/a/33951245/1819824
标签: python excel matplotlib