Reputation: 1028
I want the use the index of a pandas DataFrame as x value for a seaborn plot. However, this raises a value error.
A small test example:
import pandas as pd
import seaborn as sns
sns.lineplot(x='index',y='test',hue='test2',data=pd.DataFrame({'test':range(9),'test2':range(9)}))
It raises:
ValueError: Could not interpret input 'index'
Is it not possible to use the index as x values? What am I doing wrong? Python 2.7, seaborn 0.9
Upvotes: 35
Views: 59638
Reputation: 339220
You would need to make sure the string you provide to the x
argument is actually a column in your dataframe. The easiest solution to achieve that is to reset the index of the dataframe to convert the index to a column.
# reset the index, which results in a column named index
df = pd.DataFrame({'test':range(9),'test2':range(9)}).reset_index()
ax = sns.lineplot(x='index', y='test', data=df)
df
test test2
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
df
after reset_index
index test test2
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
Upvotes: 8
Reputation: 41
I know it's an old question, and maybe this wasn't around back then, but there's a much simpler way to achieve this:
If you just pass a series from a dataframe as the 'data' parameter, seaborn will automatically use the index as the x values.
sns.lineplot(data=df.column1)
Upvotes: 4
Reputation: 39052
I would rather prefer to use it this way. You need to remove hue
as I assume it has a different purpose which doesn't apply in your current DataFrame because you have a single line. Visit the official docs here for more info.
df=pd.DataFrame({'test':range(9),'test2':range(9)})
sns.lineplot(x=df.index, y='test', data=df)
Output
Upvotes: 49