Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

python - Plot point markers and lines in different hues but the same style with seaborn

Given the data frame below:

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))
})

I'd like to use color and only color to distinguish logic in a line plot, and mark points on values. Specifically, this is my desired output (plotted by R ggplot2):

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

desired output

I tried to do the same thing with seaborn.lineplot, and I specified markers=True but there was no marker:

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

sns no markers

I then tried adding style="logic" in the code, now the markers showed up:

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

sns with markers 1

Also I tried forcing the markers to be in the same style:

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

sns with markers 2

It seems like that I have to specify style before I can have markers. However, that causes undesired plot output since I don't want to use two aesthetic dimensions on one data dimension. That violates the principles of aesthetic mapping.

Is there any way I can have the lines and points all in the same style but in different colors with seaborn or Python visualization? (seaborn is preferred - I don't like the looping way ofmatplotlib.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can directly use pandas for plotting.

pandas via 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

The drawback here would be that the legend needs to be created manually.

pandas via pivot

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

enter image description here

seaborn lineplot

For seaborn lineplot it seems a single marker is enough to get the desired result.

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...