import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# generate data
rng = np.random.default_rng(12)
x = np.linspace(0, np.pi, 50)
y1, y2 = np.sin(x[:25]), np.cos(x[25:])
cat = rng.choice(["a", "b", "c"], 50)
data = pd.DataFrame({"x": x , "y" : y1.tolist() y2.tolist(), "cat": cat})
# generate figure
fig, ax = plt.subplots(figsize=(8, 5), ncols=2)
g0 = sns.lineplot(x="x", y="y", data=data, hue='cat', ls="--", ax=ax[0])
g1 = sns.lineplot(x="x", y="y", data=data, hue='cat', ls="--", ax=ax[1])
g1.get_lines()[0].set_color('black')
print(ax[0].get_lines())
for line in ax[0].get_lines():
print(line.get_label())
plt.tight_layout()
plt.show()
This returns a list:
<a list of 6 Line2D objects>
of which the first three objects are the coloured dotted lines in the left subplot in the figure, confirmed by changing the color of one of these lines in the right subplot.
But I am unable to understand what the last three Line2D objects are in the list ax[0].get_lines()
.
If I try to access the labels of the Line2D objects using
[line.get_label() for line in ax[0].get_lines()]
it gives ['_child0', '_child1', '_child2', 'b', 'a', 'c']
.
But the last three Line2D objects in the list don't behave like an usual Line2D object since
ax[0].get_lines()[-1].set_lw(0.2)
did not change anything perceivable in the figure.- I expected
ax[0].get_lines()[-1].remove()
would remove green colored legend line in the left subplot, but it had no effect.
So, what do the last three Line2D objects in the list ax[0].get_lines()
, which do not have the string _child
in their labels, represent?
Generated with matplotlib (v3.5.1) and seaborn (v0.11.2).
CodePudding user response:
These are dummy lines used to create the legend. Seaborn's legends can be quite complex, due to the many options. You might want to check out