Issue
i need advice. In my DB, i have x points and y points in form:
df = pd.read_sql_table('table', cnx)
id | curves |
---|---|
1 | [(x,y),(x,y),(x,y) etc.] |
2 | [(x,y),(x,y),(x,y) etc.] |
type(df['curves']) #pandas.core.series.Series
And I would like to try to plot Line Graph.
I try several solutions. but nothing worked for me.
data = df['curves']
plt.plot(*zip(*data))
plt.show()
or
data_in_array = np.array(data)
transposed = data_in_array.T
x,y = transposed #but here i got error - not enough values to unpack (expected 2, got 1)
Please advice
Solution
Explode the curves list column
df = df.explode('curves').reset_index()
Create separate x and y columns
df['curves_x'] = df.curves.str[0]
df['curves_y'] = df.curves.str[1]
Plot using seaborn
import seaborn as sns
import matplotlib.pyplot as plt
sns.lineplot(data=df, x='curves_x', y='curves_y', hue='id')
plt.show()
To understand better, let's take some sample data,
id curves
0 1 [(10, 20), (20, 30), (30, 50)]
1 2 [(10, 10), (20, 40), (30, 20)]
Explode the column and reset the index
id curves
0 1 (10, 20)
1 1 (20, 30)
2 1 (30, 50)
3 2 (10, 10)
4 2 (20, 40)
5 2 (30, 20)
Create x and y columns
id curves curves_x curves_y
0 1 (10, 20) 10 20
0 1 (20, 30) 20 30
0 1 (30, 50) 30 50
1 2 (10, 10) 10 10
1 2 (20, 40) 20 40
1 2 (30, 20) 30 20
The plot will look like this
Answered By - Vishnudev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.