I have a dataframe like this
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame({'A': [1,2,3,4,5,4,3,2,1],
'B': [200,300,400,800,1500,900,450,275,200],
'c': ['up','up','down','up','up','down','down','up','down'],
'd': ['r','r','r','r','r','r','r','r','r'],
})
When I do a line plot with seaborn with the code sns.lineplot(data=df, x='A', y='B',ci=None)
. I get a plot like below.
As you can see, the points have not completely plotted. When I do the plot with the code below
upDF = df.loc[df['c']=='up']
downDF = df.loc[df['c']=='down']
sns.lineplot(data=upDF, x='A', y='B',ci=None, label = 'up');
sns.lineplot(data=downDF, x='A', y='B',ci=None, label = 'down');
plt.legend()
I get a plot like below
In this plot, all points are plotted, but they are 'disconnected'. How can I get a plot like below with the points connected & just only one legend (column 'D' or a constant can be used for legend)
If I use sns.lineplot
on my actual data, I get the graph like below instead of up
& down
plotted separately.
CodePudding user response:
You can use pure matplotlib. Select the rows after an up as part of the up Series to ensure joining the points. For the legend, add a label that starts with an underscore to be skipped:
import matplotlib.pyplot as plt
m = df['c']=='up'
upDF = df.loc[m|m.shift()]
downDF = df.loc[~m]
ax = plt.subplot()
upDF.plot(x='A', y='B', label='r', ax=ax)
downDF.plot(x='A', y='B', label='_skip', ax=ax)
ax.legend()
output: