python - 图例颜色不匹配绘图颜色
问题描述
我正在尝试设置散点图中每个点的图例。我的主要问题是每个点的颜色与图例中的颜色不匹配。我做错了什么,我该如何纠正?
def scatter(self, indep, dep, labl):
x = self.df_input[indep]
y = self.df_input[dep]
random = np.random.RandomState(0)
colors = random.rand(len(labl)+1)
fig = plt.figure()
ax = fig.add_subplot(111)
for leg in labl:
ax.scatter(x, y, c=colors, cmap='gist_ncar', label=leg)
ax.legend()
ax.set_xlabel(indep)
ax.set_ylabel(dep)
ax.axis('tight')
plt.show()
解决方案
似乎您可能正在尝试在数据框中绘制组。所以这样的事情可能会起作用:
import matplotlib.pyplot as plt
import pandas as pd
data = [['a', 1, 3],
['a', 2, 2],
['b', 2, 4],
['b', 1, 5],
['b', 3, 5],
]
df = pd.DataFrame(data, columns=['cat', 'x', 'y'])
for name, group in df.groupby('cat'):
plt.scatter(group.x, group.y, label=name)
plt.legend()
这会产生:
推荐阅读
- encoding - 在机器人框架中将值列标题读取到 csv 时出现问题
- java - 尝试在 MAC 上克隆 GIT 时出现 javax.net.ssl.SSLHandshakeException
- sql-server - 如何同时对具有 2 个值的列进行分组和计数?
- asp.net - 谷歌身份验证 Asp.net 核心
- git - 如何从源代码更新到 Github 镜像存储库?
- html - 如何防止手动调整 md-input-container 的大小
- java - jri.dll:找不到依赖库
- javascript - 在ajax回调函数javascript中执行乱序
- python - 增加饼图 matplotlib 中标签的字体大小
- powershell - 使用powershell删除Excel中的第一个单元格