为什么不能叠加小提琴图和折线图?

huangapple go评论84阅读模式
英文:

Why can't I overlay a violinplot and a lineplot?

问题

看起来Seaborn对显示的轴标签进行了许多调整,因此我无法在上面叠加“常规”matplotlib对象。如何修复下面的行为?

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

fig, ax = plt.subplots(figsize=(10, 6))

data = pd.DataFrame()
data["value"] = np.random.normal(0, 1, 1000)
data["week"] = np.random.randint(20, 30, 1000)

# 制作小提琴图,并在其上放置一条线
sns.violinplot(data=data, x="week", y="value", scale="width", linewidth=0.5, palette="viridis")

# 对数据进行线性拟合
x = data["week"].values
y = data["value"].values
m, b = np.polyfit(x, y, 1)

y_hat = m * x + b

# 绘制线条
ax.plot(x, y_hat, color="black", linewidth=2)

为什么不能叠加小提琴图和折线图?

英文:

It appears that Seaborn does a lot of fiddling with the displayed axis labels, since I can't overlay "regular" matplotlib objects on top. How can I fix the below behavior?

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

fig, ax = plt.subplots(figsize=(10, 6))

data = pd.DataFrame()
data["value"] = np.random.normal(0, 1, 1000)
data["week"] = np.random.randint(20, 30, 1000)

# make a violin plot, and put a line on top of it
sns.violinplot(data=data, x="week", y="value", scale="width", linewidth=0.5, palette="viridis")

# fit a line to the data
x = data["week"].values
y = data["value"].values
m, b = np.polyfit(x, y, 1)

y_hat = m * x + b

# plot the line
ax.plot(x, y_hat, color="black", linewidth=2)

为什么不能叠加小提琴图和折线图?

答案1

得分: 1

这是因为 violinplotx 视为分类变量。根据文档

该函数始终将其中一个变量视为分类变量,并在相关轴上绘制数据的序数位置(0、1、...n),即使数据具有数值或日期类型也是如此。

如果你从线条 x 中减去20,你将得到在小提琴图上的线条(你可能也需要同时更改 y):

x = data["week"].values - 20

为什么不能叠加小提琴图和折线图?

英文:

That's because violinplot treats x as Categorical. From the doc:

> This function always treats one of the variables as categorical and draws data at ordinal positions (0, 1, … n) on the relevant axis, even when the data has a numeric or date type.

If you subtract 20 to the line x, you'll get the line over the violin plots (you might want to change y as well though):

x = data["week"].values - 20

为什么不能叠加小提琴图和折线图?

huangapple
  • 本文由 发表于 2023年6月1日 15:52:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76379758.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定