如何正确地将Seaborn色调添加到图形中?

时间:2019-01-28 21:42:12

标签: python plot seaborn

我有一个非常简单的两个人的数据框:

我想以正确的色调绘制它,因此生成了图例

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

d = {"John":[43, 23, 12], "Mary":[24, 53, 32],"Trial_#":[1,2,3]}
df = pd.DataFrame(data=d)
fig = sns.pointplot(x='Trial_#', y='John',
data = df)
fig = sns.pointplot(x='Trial_#', y='Mary',
data = df)

sns.set_context("notebook", font_scale=1)
fig.set(ylabel="Guess")
fig.set(xlabel="Trial")
plt.show()

我该怎么做?

2 个答案:

答案 0 :(得分:0)

如果可以使用matplotlib代替seaborn的{​​{1}},则可以简单地执行以下操作

pointplot

enter image description here

答案 1 :(得分:0)

使用matplotlib

关键是将索引设置为试验编号列,以便其余列包含要绘制的值。然后,可以将数据帧直接提供给matplotlib的plot函数。一个小缺点是,图例需要单独创建。

import matplotlib.pyplot as plt
import pandas as pd

d = {"John":[43, 23, 12], "Mary":[24, 53, 32], "Trial_#":[1,2,3]}
df = pd.DataFrame(data=d)
df = df.set_index("Trial_#")

lines = plt.plot(df, marker="o")
plt.ylabel("Guess")
plt.legend(lines, df.columns)

plt.show()

enter image description here

使用熊猫

您可以直接使用熊猫进行绘图,这具有免费提供传说的优点。

import matplotlib.pyplot as plt
import pandas as pd

d = {"John":[43, 23, 12], "Mary":[24, 53, 32], "Trial_#":[1,2,3]}
df = pd.DataFrame(data=d)

ax = df.set_index("Trial_#").plot(marker="o")
ax.set(ylabel="Guess")

plt.show()

enter image description here

使用Seaborn

最复杂的解决方案是使用Seaborn。 Seaborn使用长格式数据框。要将宽格式数据框转换为长格式数据框,可以使用pandas.melt。然后,生成的长格式框架将包含一列,其中包含名称;这些可以在seaborn中用作hue变量。

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

d = {"John":[43, 23, 12], "Mary":[24, 53, 32], "Trial_#":[1,2,3]}
df = pd.DataFrame(data=d)

dfm = pd.melt(df, id_vars=['Trial_#'], value_vars=['John', 'Mary'], 
                  var_name="Name", value_name="Guess")
ax = sns.pointplot(x='Trial_#', y='Guess', hue="Name", data = dfm)

plt.show()

enter image description here