英文:
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
这是因为 violinplot
将 x
视为分类变量。根据文档:
该函数始终将其中一个变量视为分类变量,并在相关轴上绘制数据的序数位置(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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论