2

Now I have a dataframe like that:

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

In excel, I can draw a "line with marker" graph with 2 level of xticklabels: categrory1 and category2.

Is there any good method to draw a similar plot using python matplotlib ?

enter image description here

So far, I can only add 1 level of 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()

enter image description here

ouxiaogu
  • 151
  • 1
  • 11
  • Since you're already using pandas, is a pandas plotting functions answer sufficient? Check out the second example [here](http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#visualization-table), for example. You should be able to pass a Series of the values you want below the table, which I think is closer to what you're trying to mimic in Excel. – James Nov 26 '15 at 14:23
  • @James, thanks for your reminder, here is the pandas plotting result: http://stackoverflow.com/a/33951245/1819824 – ouxiaogu Nov 27 '15 at 06:13

1 Answers1

0

Thanks to James' reminder, using the pandas plot, I can merge 2 category into 1 xtick labels, but still not exactly what I want.

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

enter image description here

ouxiaogu
  • 151
  • 1
  • 11