ValueError: Could not interpret input 'index' when using index with seaborn lineplot
Question:
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
Answers:
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
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.
sns.lineplot(x='index', y='test', data=pd.DataFrame({'test':range(9),'test2':range(9)}).reset_index())
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)
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
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
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.
sns.lineplot(x='index', y='test', data=pd.DataFrame({'test':range(9),'test2':range(9)}).reset_index())
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)