garrettj403 / SciencePlots

Matplotlib styles for scientific plotting

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Help Request]: color reuse

Mingzefei opened this issue · comments

Environment

System: Linux-5.15.90.1-microsoft-standard-WSL2-x86_64-with-glibc2.31
Python: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0]
SciencePlots: 2.1.0
Matplotlib: 3.8.0
Latex distro: (populate manually)

Describe your issue here

image
Is there a good way to achieve this: the line presented fit1 in the above picture reuses the color of data1, and the line presented fit2 reuses the color of data2?
By the way, I drew the above image using four plot commands.
Looking forward to your help and thank you for implementing a great tool.

How can we reproduce it? What have you tried?

import random
import numpy as np
import matplotlib.pyplot as plt
import scienceplots
plt.style.use('science')

# data
x1 = range(10)
y1 = [x + random.randint(1, 2) for x in x1]
y1_fit = np.polyfit(x1, y1, 1)
x2 = range(-2, 8)
y2 = [x + random.randint(1, 5) for x in x2]
y2_fit = np.polyfit(x2, y2, 1)

# plot 
plt.plot(x1, y1, 'o', label='data 1')
plt.plot(x2, y2, 'o', label='data 2')
plt.plot(x1, np.polyval(y1_fit, x1), '--', label='fit 1')
plt.plot(x2, np.polyval(y2_fit, x2), '--', label='fit 2')
plt.legend()
plt.show()

Extra info

No response

I googled and found that this code can be used to achieve the above purpose.

plt.plot(x1, y1, 'o', label='data 1')
plt.plot(x2, y2, 'o', label='data 2')
plt.plot(x1, np.polyval(y1_fit, x1), '--', label='fit 1', color=plt.gca().lines[0].get_color())  # Set the color to match the first data
plt.plot(x2, np.polyval(y2_fit, x2), '--', label='fit 2', color=plt.gca().lines[1].get_color())  # Set the color to match the second 

But this code is too bloated. Is there a better way?

You can use the color parameter passed to plt.plot with:

E.g.: plt.plot(x, y, color='purple')

This parameter changes the color applied to whatever is plotted with that plt.plot.

Hope to have helped you. I'll close this issue since this is not related to SciencePlots.