【发布时间】: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