看下面的代碼
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
plot_df = pd.DataFrame(index=np.arange(5), columns=["Series 1", "Series 2"], data=np.array([[1, 2],[2.4, 5],[4.1, 7.1],[5, 8.9],[5.2, 10]]))
plot_df_points = pd.DataFrame(index = [1.5, 2, 3.7], columns = ["Series 1", "Series 2"], data=np.array([[1.2, 3.4],[4.5, 6.9],[5.5, 9.6]]))
df = pd.DataFrame(plot_df.stack()).reset_index()
df.columns = ["x", "Series","y"]
df_points = pd.DataFrame(plot_df_points.stack()).reset_index()
df_points.columns = ["x", "Series","y"]
fig, ax = plt.subplots()
sns.lineplot(data=df,x="x",y="y", hue="Series",ax=ax,palette="rocket",linewidth=2.5)
sns.scatterplot(data=df_points, x="x", y="y", hue="Series", ax=ax,s=200)
plt.show()
plt.close()
我想為同一系列有相同的顏色/圖例。即線圖中系列一的顏色應與散點圖中相同。如何做到這一點?
uj5u.com熱心網友回復:
您需要在 中設定與 中相同的scatterplot調色板lineplot。或者在這兩種情況下都使用默認值(省略palette=)。
要組合圖例,您可以使用元組圖例處理程式 ( HandlerTuple)。
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
import seaborn as sns
import pandas as pd
import numpy as np
plot_df = pd.DataFrame(index=np.arange(5), columns=["Series 1", "Series 2"],
data=[[1, 2], [2.4, 5], [4.1, 7.1], [5, 8.9], [5.2, 10]])
plot_df_points = pd.DataFrame(index=[1.5, 2, 3.7], columns=["Series 1", "Series 2"],
data=[[1.2, 3.4], [4.5, 6.9], [5.5, 9.6]])
df = plot_df.rename_axis('x').reset_index().melt(id_vars='x', var_name='Series', value_name='y')
df_points = plot_df_points.rename_axis('x').reset_index().melt(id_vars='x', var_name='Series', value_name='y')
fig, ax = plt.subplots()
sns.lineplot(data=df, x="x", y="y", hue="Series", ax=ax, palette="rocket", linewidth=2.5)
sns.scatterplot(data=df_points, x="x", y="y", hue="Series", ax=ax, palette="rocket", s=200)
handles, labels = ax.get_legend_handles_labels()
ax.legend([tuple(handles[::2]), tuple(handles[1::2])], labels[:2], handlelength=3,
handler_map={tuple: HandlerTuple(ndivide=None)})
plt.tight_layout()
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/415787.html
標籤:
