【问题标题】:Seaborn: How to change size of spots in a JointPlot according to feature?Seaborn:如何根据特征改变 JointPlot 中点的大小?
【发布时间】:2021-12-18 05:44:16
【问题描述】:

我有下面的代码。您可以看到绘制了一个 JointPlot。

但我希望点的大小随着“大小”列的值而变化。

所以我把最后一行marker='o') 改成了marker='o', s = "size")。现在我收到错误消息AttributeError: 'Line2D' object has no property 's'

我希望每个点的大小都不同(即类似于this)。如何修改我的代码来实现这一点?

import seaborn as sns
import numpy as np
from itertools import product
sns.set(style="darkgrid")

tips = sns.load_dataset("tips")
g = sns.jointplot("total_bill", "tip", data=tips, kind="reg",
                  xlim=(0, 60), ylim=(0, 12), color='k', size = 7)

#Clear the axes containing the scatter plot
g.ax_joint.cla()

# #Plot each individual point separately
for i,row in enumerate(tips.values):
    g.ax_joint.plot(row[0], row[1], color="blue", marker='o')

更新:

我也试过直接合并两个情节,但还是不行。没有报错,只是散点图只是贴到右边了……

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from itertools import product
sns.set(style="darkgrid")

tips = sns.load_dataset("tips")

fig, ax = plt.subplots()

g = sns.jointplot("total_bill", "tip", data=tips, kind="reg",
                  xlim=(0, 60), ylim=(0, 12), color='k', size = 7)

#Clear the axes containing the scatter plot
g.ax_joint.cla()

ax2 = ax.twinx()

sns.scatterplot(
    data=tips, x="total_bill", y="tip", hue="size", size="size",
    sizes=(20, 200), legend="full"
)

plt.show()

【问题讨论】:

  • @JohanC 谢谢。在最后一行,g.ax_joint.scatter(row[0], row[1], color="blue", marker='o', s=7) 有效,但 g.ax_joint.scatter(row[0], row[1], color="blue", marker='o', s="size") 仍然无效,这是我的主要意图...我希望点具有不同的大小...
  • fig, ax = plt.subplots() 在这里不起作用,因为jointplot 是一个创建新图形的图形级函数。你需要sns.scatterplot(..., ax=g.ax_joint)

标签: python plot seaborn data-visualization visualization


【解决方案1】:

您可以在 g.ax_joint 上创建 seaborn 散点图。以下代码已在 seaborn 0.11.2 上测试过(旧版本可能存在名为“size”的列的问题)。

import seaborn as sns
import numpy as np

sns.set(style="darkgrid")

tips = sns.load_dataset("tips")
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind="reg",
                  xlim=(0, 60), ylim=(0, 12), color='k')
g.ax_joint.cla()
sns.scatterplot(data=tips, x='total_bill', y='tip', size='size', sizes=(10, 200),
                ax=g.ax_joint)

如cmets中所说,为了保持回归线,可以使用sns.jointplot(..., scatter=False)

g = sns.jointplot(x="total_bill", y="tip", data=tips, kind="reg", scatter=False,
                  xlim=(0, 60), ylim=(0, 12), color='k')
sns.scatterplot(data=tips, x='total_bill', y='tip',
                hue='size', palette='husl',
                size='size', sizes=(10, 200), legend='full',
                ax=g.ax_joint)

【讨论】:

  • 也许在jointplot 调用中执行scatter=False,然后不清除坐标轴,这样您将获得尺寸映射和回归线(这似乎是需要的)?
猜你喜欢
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多