python - 如何正确地将 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()
我该怎么做呢?
解决方案
使用 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
. 生成的长格式框架随后包含一列,其中包含名称;这些可以用作hue
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)
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()
推荐阅读
- html - 如何更改 pickerInput 元素的容器颜色?
- powerbi - 具有用户输入的 DAX PowerBI 平均值总和
- python - 我无法从 python 的标准库中加载模块
- php - 从 PHP 调用已编译的 C++ 可执行文件以创建套接字
- c# - 了解 debugDiag 报告
- c# - 向 Task.WaitAll 添加延迟
- r - 如何在 r 中使用 caret 包来调整神经网络的详细结构
- spring - Sql 只插入空数据,vaadin 14
- javascript - 如何通过 CommonJS 模块使用 webpack 和 ES6 与依赖项?
- c# - 切换显示器时未触发 BrightnessOverride.IsSupportedChanged