【问题标题】:Scatter plot legend shows only one variable with color -Pandas Seaborn散点图图例仅显示一个带有颜色的变量 -Pandas Seaborn
【发布时间】:2018-01-27 15:11:27
【问题描述】:

我正在尝试使用seaborn 包在pandas 中绘制scatter 绘图。我希望我的两个变量都显示在图例中,但我只得到一个。以下是我所做的:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns 

df = pd.DataFrame(np.random.randn(100, 6), columns=['a', 'b', 'c', 'd', 'e', 'f'])

我是这样设计的,

plt.scatter(df['a'],df['b'], color = ['red', 'blue'])
plt.legend(loc = 'best')
plt.show()

我得到这样的图像,

如您所见,我没有看到蓝色的 a 列/对象。我在这里犯了什么错误?我搜索了这个,还没有运气。任何建议将不胜感激。

【问题讨论】:

  • 你正在用(x, y) 坐标在x=df['a']y=df['b'] 处绘制点 - 这就是你想要的吗?
  • @MaxU 是的,这就是我想要的。我希望图例以蓝色显示a,以红色显示b,反之亦然
  • x坐标是a,y坐标是b,所以你的图例是正确的。
  • @mauve,是的,正确,但在我的传说中,它应该同时显示颜色和坐标,不是吗?
  • @innm,我不明白 - 你有 一个 点的 (x,y) 坐标,所以传说是正确的......而且它们的颜色是这样的: red, '蓝色', red, ...

标签: python pandas plot scatter-plot


【解决方案1】:

更新:

plt.scatter(df.index, df.a, color='red')
plt.scatter(df.index, df.b, color='blue')
plt.legend(loc = 'best')

结果:


我觉得你很困惑。

演示:

假设您的 DF 中只有三行:

In [53]: df = pd.DataFrame({'x':[1,2,3], 'y':[5,6,7]})

In [55]: df
Out[55]:
   x  y
0  1  5
1  2  6
2  3  7

您正在尝试绘制以下 三个 点 - 您期望什么样的图例?

In [54]: plt.scatter(df.x, df.y, color=['red','blue'])
Out[54]: <matplotlib.collections.PathCollection at 0x149f9f28>

In [56]: plt.legend(loc = 'best')
Out[56]: <matplotlib.legend.Legend at 0x1353ca20>

【讨论】:

  • 感谢您的努力澄清,更新是我正在寻找的。​​span>
  • @i.n.n.m,很高兴我能帮上忙 :)
猜你喜欢
  • 2017-11-22
  • 2015-05-28
  • 2019-05-25
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
相关资源
最近更新 更多