0

I am attempting to write a function that can plot a best fit curve and its original data points. I would ideally like to run the function for 4-5 data sets and have them all appear on the same figure. The function I have at the moment does this well for plotting the best fit curve, but when I add in the individual data points they show up as a different colour to the best fit curve.

Output from my function

I would like them both to be the same colour so that when I run the function 4-5 times it is not too messy with 10 or so different colours. Ideally I would like the output to be like this

Ideal Output

My code:

def plot(k, w, lab):
popt, pcov = cf(linfunc, np.log(k), np.log(w))
yfit = linfunc(np.log(k), *popt)
plt.plot(np.log(k), yfit, '-', label = lab)
plt.plot(np.log(k), np.log(w), 'o')
plt.legend();

plot(k2ml, w2ml, '2ml')

Additionally, is there a way that I could make my function take any input for the parameter "lab" and have it automatically converted to a string so it can be used in the legend?

1
  • 1
    You can do this with matplotlib and scipy curve fit but the easiest approach would be seaborn because it has integrated both conveniently. Whatever approach you choose, ideally, all data should be handed over in one piece - otherwise, you have to manually sort out the colors. Commented Mar 4, 2022 at 7:02

1 Answer 1

1

So what You want is to plot line and it's fit in the same colors.
To achieve Your goal, You can plot first line, get it's color and then set this color to the fit line.

Here is small code snippet doing that:

# Plot first line and get list of plotted lines
lines = plt.plot([0,1,2,3,4], [5,6,7,8,9])
# Get color of first (and only) line
line_color = lines[0].get_color()
# Plot Your fit with same color parameter
plt.plot([0,1,2,3,4], [0,1,2,3,4], color=line_color)

As for label, I would just convert it into string with str(lab).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.