Home > other >  How to smooth lines in a figure in Pandas?
How to smooth lines in a figure in Pandas?

Time:04-13

I have this table: The data in the table

I want to modify the graph by converting the lines into smooth lines, this how the graph looks like now: The current graph

This is my code:

import pandas as pd
import seaborn as sns
plotDf = pd.read_csv('myFile.csv')
sns.lineplot(
    data=plotDf,
    x= "Hum", y= "Fam", hue="Genfer", style="Genfer",
    markers=True, dashes=False
)

This is an example: Smooth Lines Graph

CodePudding user response:

What you're asking is unclear.

If you wish a smooth line, you could fit splines or a polynomial to your data. See https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html

If you wish to model some generating process which produced that data, well, that's a bigger topic. In general a "smooth" curve might not go through all data points, so you will need to specify a loss function that expresses your willingness to have the curve go through just a subset of those points. OLS ordinary least squares offers an example of one possible tradeoff.

CodePudding user response:

I've had good luck with Scipy's Akima interpolation.
See Update 2 here for more about it & an example.
I was using it with Seaborn's lineplot as well.

I'd convert your code to illustrate; however, because you provided your sample data as an image instead of actual text data or code that could be used, it's not as easy it would be if you provided a minimal reproducible example, and so I'll leave it to you. Luckily, the example I referenced includes working code and it should be obvious how to set up the interpolation and the linspace spanning your minimal and maximal x. You'll need to subset out based on Male and Female to pass each set into the interpolation. You may need more than 1000 points there if your spanner is a lot wider than the example. It should be obvious from the example how to adapt it the sns.lineplot. You'll need two lines on your plot; you can use the ax option sns.lineplot has, see here.

  • Related