【问题标题】:How to add a legend in a pandas DataFrame scatter plot?如何在 pandas DataFrame 散点图中添加图例?
【发布时间】:2020-03-27 04:47:04
【问题描述】:

我有一个 pandas DataFrame,其中包含以下感兴趣的列:

['Relative Width', 'Relative Height', 'Object Name', 'Object ID']

df.plot(c='Object ID') 确定的 15 个对象名称有 15 种颜色,生成下图:

我想显示一个包含 15 个对象名称的图例,如何做到这一点?

import matplotlib.pyplot as plt
from annotation_parsers import parse_voc_folder


def visualize_box_relative_sizes(folder_path, voc_conf, cache_file='data_set_labels.csv'):
    frame = parse_voc_folder(folder_path, voc_conf, cache_file)
    title = f'Relative width and height for {frame.shape[0]} boxes.'
    frame.plot(
        kind='scatter',
        x='Relative Width',
        y='Relative Height',
        title=title,
        c='Object ID',
        colormap='gist_rainbow',
        colorbar=False,
    )
    plt.show()

根据wwnde的推荐,我把代码改成如下:

def visualize_box_relative_sizes(folder_path, voc_conf, cache_file='data_set_labels.csv'):
    frame = parse_voc_folder(folder_path, voc_conf, cache_file)
    title = f'Relative width and height for {frame.shape[0]} boxes.'
    sns.scatterplot(x=frame["Relative Width"], y=frame["Relative Height"], hue=frame["Object Name"])
    plt.title(title)
    plt.show()

产生以下结果:

【问题讨论】:

  • 什么是parse_voc_folder?你能帮我们把它存根吗?
  • 可能不得不走这条路 - stackoverflow.com/questions/37812325/…
  • @DerekEden 我在拥有 10,000 行的数据帧上尝试了这种方法,它运行了大约 30 秒而没有给出任何结果,所以我认为这是一种非常低效的方法。
  • @Z4-tier 我不想在这里使事情复杂化,无论如何它是一个返回具有 8 列的数据帧的函数,其中我在上面提到了 4 列,它们是感兴趣的列,其余的数据框与我的问题无关。
  • 为什么不 fig, ax = plt.subplots() ax = sns.scatterplot(x="Relative Width", y="Relative Height", hue="Relative Height", size="size ", 数据=提示) plt.show() ?这会给你一个图例和默认分配的颜色?

标签: python python-3.x pandas matplotlib


【解决方案1】:

请尝试

fig, ax = plt.subplots()

ax = sns.scatterplot(x="total_bill", y="tip",
                     hue="size", size="size",
                     data=tips)
ax.set_title('title')
plt.show()

这应该会给你一个默认的彩色图例

【讨论】:

  • 我尝试了这种方法,它奏效了,我将编辑我的问题以包含结果,如何修改此设置的 cmap?
  • @sK500 添加参数palette = 'gist_rainbow'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
  • 2020-08-15
  • 2019-08-22
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
相关资源
最近更新 更多