Seaborn lineplot 使用一个分组变量进行着色分别绘制所有条目(线)

问题描述 投票:0回答:2

我正在尝试使用一个变量来绘制数据框中的所有条目以用于图例目的。我的数据框看起来像:

如果我尝试通过 sns.lineplot 和 Hue='Punto' 进行绘图,它会聚合所有条目。

ax = sns.lineplot(data = dfnew, x = 'Profundidad', y= 'OD', marker = 'o', hue='Punto')
ax.set(xlabel = 'Profundidad (m)',
       ylabel = 'Oxígeno disuelto (mg/L)',
       title = 'Oxígeno disuelto - Profundidad RCNP',
       xlim=(0.4, 3))
fig = plt.gcf()
fig.set_size_inches(10, 5)

我尝试了两种不同的方法: (1) 删除估计器,但它将一天的“结束”点与第二天的“开始”点连接起来。

ax = sns.lineplot(data = dfnew, x = 'Profundidad', y= 'OD', marker = 'o', hue='Punto', estimator=None, sort=False)
ax.set(xlabel = 'Profundidad (m)',
       ylabel = 'Oxígeno disuelto (mg/L)',
       title = 'Oxígeno disuelto - Profundidad RCNP',
       xlim=(0.4, 3))
fig = plt.gcf()
fig.set_size_inches(10, 5)

(2) 通过使用色调和样式来使用两个不同的分组变量(绘制我想要的,但具有不同的样式)

ax = sns.lineplot(data = dfnew, x = 'Profundidad', y= 'OD', marker = 'o', hue='Punto', style='Fecha')
ax.set(xlabel = 'Profundidad (m)',
       ylabel = 'Oxígeno disuelto (mg/L)',
       title = 'Oxígeno disuelto - Profundidad RCNP',
       xlim=(0.4, 3))
fig = plt.gcf()
fig.set_size_inches(10, 5)

换句话说,我想要第二个图,但仅使用“第一个”图例(hue='Punto')。

有人可以帮助我吗?非常感谢!

python pandas plot seaborn
2个回答
1
投票

好吧,我使用了不同的方法,使用默认的 pandas 绘图函数(没有我想要的那么快或简单,但它有效)。

from matplotlib.lines import Line2D

fig, ax = plt.subplots()
colors = sns.color_palette()
puntos = dfnew['Punto'].unique()
for n, punto in enumerate(puntos):
  subset = dfnew[dfnew['Punto'] == punto]
  registros = subset['Fecha'].unique()
  c = colors[n]
  for registro in registros:
    subset[subset['Fecha'] == registro].plot(x = 'Profundidad', y = 'OD', marker = 'o', alpha=0.75, color = c, markeredgecolor = 'white', ax=ax)

lines = [Line2D([0], [0], color=c, linewidth=2, alpha=0.75) for c in colors[:len(puntos)]]
ax.legend(lines, puntos)
ax.set_xlabel('Profundidad (m)')
ax.set_ylabel('Oxígeno disuelto (mg/L)')
ax.set_title('Oxígeno disuelto - Profundidad RCNP')
fig.set_size_inches(10, 5)

0
投票

Seaborn 解决方案:使用

style
参数代替
units
,并使用
estimator = None
:

ax = sns.lineplot(data = dfnew, x = 'Profundidad', y= 'OD', marker = 'o', hue='Punto', units='Fecha', estimator = None)

感谢您发表这篇文章。我有同样的问题。您使用

style
的方式启发我在文档中找到
units
参数

https://seaborn.pydata.org/ generated/seaborn.lineplot.html

© www.soinside.com 2019 - 2024. All rights reserved.