首页 > 解决方案 > 如何正确地将 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()

我该怎么做呢?

标签: pythonplotseaborn

解决方案


使用 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()

在此处输入图像描述

使用熊猫

可以直接用pandas绘图,好处是免费给你一个传奇。

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

在此处输入图像描述

使用 Seaborn

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

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

在此处输入图像描述


推荐阅读