【问题标题】:Pyplot scatter size and color not matchingPyplot 散点图大小和颜色不匹配
【发布时间】:2018-10-18 20:28:42
【问题描述】:

我正在尝试从 pandas 数据框创建简单的散点图,将 column1 与 column2 进行对比,并使用 column3(布尔值)作为颜色和大小。然而,尽管颜色和大小数组按预期匹配,但它们适用于图中的不同点。

>>> colors = ['white' if not val else 'red' for val in df.column3.values]
>>> size = [5 if not val else 30 for val in df.column3.values]
>>> plt.scatter(df['column1'].values, df['column2'].values, c=colors, s=size)
>>> print zip(colors, size)
[('white', 5),
 ('white', 5),
 ('red', 30),
 ('red', 30),
 ('white', 5),
 ...]

为什么会这样?

E:澄清一下,color 和 size 数组中的每个元素都是正确配对的:

>>> for pair in zip(colors, size):
...     if (pair[0] == 'white' and pair[1] != 5) or (pair[0] == 'red' and pair[1] != 30):
...         print pair
[]

【问题讨论】:

  • 你的意思是在第二行写“in df.column**3**.values”吗?
  • @DizietAsahi 是的,我做到了 - 谢谢!
  • 如果您有大量元素,那不验证配对是否正确。你不能理智地目视检查。您需要使用断言进行过滤。类似assert len(zip(colors, size)) == len([x for x in zip(colors, size) if (x[0] == 'white' and x[1] == 30) or (x[0] == 'red' and x[1] == 5)])
  • 诚然,它们应该是相同的,因为它们都是以相同的方式生成的......

标签: python matplotlib seaborn


【解决方案1】:

为什么会这样?

可能是因为不能保证(通常)有两个不同的数据框列在同一个位置有 Falsey 数据。

>>> colors = ['white' if not val else 'red' for val in df.column3.values]
>>> size = [5 if not val else 30 for val in df.column2.values]

colors 是从 df.column3 创建的,size 是从 df.column2 创建的(我想也许你的意思是从 df.column3 生成 size。

对于列中的虚假数据,不能保证'white' 将始终与5 配对,并且'red' 将始终与30 配对。如果您希望'white' 始终与5 配对,而'red' 始终与30 配对,那么最好根据颜色生成您的尺寸:

>>> colors = ['white' if not val else 'red' for val in df.column3.values]
>>> size = [5 if val == 'white' else 30 for val in colors]

那么你就不能得到不匹配。

HTH。

【讨论】:

  • 你是对的 - 我也在从 column3 生成size。我在重命名列以公开发布时输入错误。
  • 这是有道理的,但是当zipping 数组在一起时,在我的colors 和size 数组中,“red”总是与 30 配对,“white”总是与 5 配对,所以看来我的数组是正确的。
  • 哦。他们仍然不匹配?
  • @Tim 好吧,也许对于第一对来说它看起来是正确的。但是你不能仅仅通过查看前几个元素就说它对每个元素都是正确的。
  • 你是对的 - 我将编辑我的问题以明确数组中的每个元素都是正确的。
【解决方案2】:

这个问题已经解决了。 column1 和 column2 中存在未绘制的空值,但在 color 和 size 数组中未跳过这些空值。您需要确保仅使用其他两列都不为空的行创建 color 和 size 数组,例如,

>>> tmpdf = df[~pd.isnull(df['column1']) & ~pd.isnull(df['column2]')]
>>> colors = ['white' if not val else 'red' for val in tmpdf.column3.values]
>>> size = [5 if not val else 30 for val in tmpdf.column3.values]
>>> plt.scatter(tmpdf['column1'].values, tmpdf['column2'].values, c=colors, s=size)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多