绘制不同色调的点标记和线条,但与seaborn相同的风格

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

鉴于以下数据框:

import pandas as pd
df = pd.DataFrame({
    "n_index": list(range(5)) * 2,
    "logic": [True] * 5 + [False] * 5,
    "value": list(range(5)) + list(range(5, 10))
})

我想使用颜色和唯一的颜色来区分线条图中的logic,以及values上的标记点。具体来说,这是我想要的输出(由R ggplot2绘制):

ggplot(aes(x = n_index, y = value, color = logic), data = df) + geom_line() + geom_point()

desired output

我试图用seaborn.lineplot做同样的事情,我指定了markers=True,但没有标记:

import seaborn as sns
sns.set()
sns.lineplot(x="n_index", y="value", hue="logic", markers=True, data=df)

sns no markers

然后我尝试在代码中添加style="logic",现在标记出现了:

sns.lineplot(x="n_index", y="value", hue="logic", style="logic", markers=True, data=df)

sns with markers 1

此外,我尝试强制标记为相同的样式:

sns.lineplot(x="n_index", y="value", hue="logic", style="logic", markers=["o", "o"], data=df)

sns with markers 2

在我有标记之前,我似乎必须指定style。但是,这会导致不希望的绘图输出,因为我不想在一个数据维度上使用两个美学维度。这违反了审美映射的原则。

有没有什么方法可以使用seaborn或Python可视化的相同样式但不同颜色的线条和点? (seaborn是首选 - 我不喜欢matplotlib的循环方式。)

python data-visualization seaborn aesthetics
2个回答
1
投票

您可以直接使用pandas进行绘图。

通过groupby的熊猫

fig, ax = plt.subplots()
df.groupby("logic").plot(x="n_index", y="value", marker="o", ax=ax)
ax.legend(["False","True"])

enter image description here

这里的缺点是需要手动创建图例。

大熊猫通过枢轴

df.pivot_table("value", "n_index", "logic").plot(marker="o")

enter image description here

seaborn lineplot

对于seaborn lineplot,似乎单个标记足以获得所需的结果。

sns.lineplot(x="n_index", y="value", hue="logic", data=df, marker="o")

enter image description here


1
投票

您需要将dashes参数设置为False,并将网格的样式指定为"darkgrid"

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "n_index": list(range(5)) * 2,
    "logic": [True] * 5 + [False] * 5,
    "value": list(range(5)) + list(range(5, 10))
})

sns.set_style("darkgrid")
sns.lineplot(x="n_index", dashes=False, y="value", hue="logic", style="logic", markers=["o", "o"], data=df)
plt.show()

enter image description here

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