user270199
user270199

Reputation: 1417

Connect points based on same value in matplotlib

Given this example:

df = pd.DataFrame({'a': ['foo', 'foo', 'bar', 'baz', 'baz', 'baz', 'foobar'], 'x': [3, 4, 1, 5, 5.5, 5.2, 8]})

How can I draw a line plot connecting the data points that have the same 'a', e.g. connect points 3 and 4 because 'foo' is the same, whereas the last data point, 8 is plotted as just a dot, by itself.

Upvotes: 0

Views: 142

Answers (1)

Nk03
Nk03

Reputation: 14949

One way:

df.reset_index().pivot_table(index=  'index', columns= 'a', values = 'x').plot(marker = '*')

Alternative via seaborn:

import seaborn as sns
sns.lineplot(x = 'index', y = 'x' , hue = 'a', data = df.reset_index(), marker = '*')

OUTPUT:

enter image description here

Upvotes: 1

Related Questions