【问题标题】:Matplotlib - Adding legend to scatter plot [duplicate]Matplotlib - 向散点图添加图例 [重复]
【发布时间】:2021-01-28 12:38:19
【问题描述】:

我正在为大家阅读熊猫书。在第 3 章中,作者使用以下代码创建了一个散点图:

# create a color variable based on sex
def recode_sex(sex):
    if sex == 'Female':
        return 0
    else:
        return 1

tips['sex_color'] = tips['sex'].apply(recode_sex)

scatter_plot = plt.figure(figsize=(20, 10))
axes1 = scatter_plot.add_subplot(1, 1, 1)
axes1.scatter(
    x=tips['total_bill'],
    y=tips['tip'],

    # set the size of the dots based on party size
    # we multiply the values by 10 to make the points bigger
#     and to emphasize the differences
    s=tips['size'] * 90,

#     set the color for the sex
    c=tips['sex_color'],

    # set the alpha value so points are more transparent
    # this helps with overlapping points
    alpha=0.5
)

axes1.set_title('Total Bill vs Tip Colored by Sex and Sized by Size')
axes1.set_xlabel('Total Bill')
axes1.set_ylabel('Tip')

plt.show()

剧情如下:

我的问题是如何在散点图中添加图例?

【问题讨论】:

  • scatter_plot.legend()你可以试试这个
  • 这能回答你的问题吗? Matplotlib scatter plot legend
  • @funie200,我才刚开始,这一切都没有,你能给我举个例子吗?
  • @r-beginners 我遇到了No handles with labels found to put in legend 错误。
  • @Cody 尽管您的问题已经得到解答,但我建议您从基本的 matplotlib 教程开始。喜欢the official tutorials

标签: python matplotlib scatter-plot


【解决方案1】:

这里有一个解决方案。此代码基于Matplotlib's tutorial on scatter plot with legends。按性别分组的数据集的循环允许生成每个性别的颜色(和相应的图例)。然后从scatter 函数的输出中指示大小,使用legend_elements 作为大小。

这是我使用您的示例中使用的数据集获得的:

代码如下:

import matplotlib.pyplot as plt
import seaborn as sns

# Read and group by gender
tips = sns.load_dataset("tips")
grouped = tips.groupby("sex")

# Show per group
fig, ax = plt.subplots(1)
for i, (name, group) in enumerate(grouped):
    sc = ax.scatter(
        group["total_bill"],
        group["tip"],
        s=group["size"] * 20,
        alpha=0.5,
        label=name,
    )

# Add legends (one for gender, other for size)
ax.add_artist(ax.legend(title='Gender'))
ax.legend(*sc.legend_elements("sizes", num=6), loc="lower left", title="Size")
ax.set_title("Scatter with legend")

plt.show()

【讨论】:

  • 我刚开始做可视化,你能提供一个纯matplotlb的解决方案吗?
  • 你的意思是,不按性别分组?因为这是一个非常纯粹的 Matplotlib 解决方案,因为它是 Matplotlib 教程的直接适配器。
  • 注意我导入seaborn只是为了加载数据;它根本不参与绘图解决方案。