繁体   English   中英

Matplotlib:向散点图添加颜色图例

[英]Matplotlib: Add color legend to scatter plot

有表为:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

list_1=[['AU',152,474.0],
        ['CA',440,482.0],
       ['DE',250,564.0,],
       ['ES',707,549.0,],
       ['FR',1435,551.0,],
       ['GB',731,555.0,],
       ['IT',979,600.0,],
       ['NDF',45041,357.0,],
       ['NL',247,542.0,],
       ['PT',83,462.0,],
       ['US',20095,513.0,],
       ['other',3655,526.0,]]
labels=['country_destination','num_users','avg_hours_spend']
df=pd.DataFrame(list_1,columns=labels)
df=df.set_index('country_destination')
df

country_destination num_users   avg_hours_spend 
AU                     152        474.0
CA                     440        482.0
DE                     250        564.0
ES                     707        549.0
FR                     1435       551.0
GB                     731        555.0
IT                     979        600.0
NDF                    45041      357.0
NL                     247        542.0
PT                     83         462.0
US                     20095      513.0
other                  3655       526.0

我需要制作散点图:

y = df['avg_hours_spend']
x = df['num_users']
N=12
colors = np.random.rand(N)
plt.scatter(x, y,c=colors)

plt.title('Web Sessions Data of Users')
plt.xlabel('No.Of.Users')
plt.ylabel('Mean Hours Users Spends on the Website')
plt.legend()
plt.show()

每种颜色代表不同国家的散点图

在此处输入图片说明

需要:我想制作大圆圈并在右侧添加图例,因为每个国家/地区的颜色都会不同。 如何 ?

在 matplotlib 中,您可以为每个国家/地区(即数据框索引的每个级别)添加不同的散点,并将s参数设置为您想要的任何值(因为您想要更大的点,我添加了s=100

for i, row in df.iterrows():
    plt.scatter(x=row.num_users, y=row.avg_hours_spend, label=i, s=100)

plt.title("Web Sessions Data of Users")
plt.xlabel("No.Of.Users")
plt.ylabel("Mean Hours Users Spends on the Website")
plt.legend()
plt.show()

在此处输入图片说明

您可以使用 seaborn 使用不同的语法获得类似的结果:

import seaborn as sns

ax = sns.scatterplot(
    x="num_users",
    y="avg_hours_spend",
    hue="country_destination",
    s=100,
    data=df.reset_index(),
)

ax.set_title("Web Sessions Data of Users")
ax.set_xlabel("No.Of.Users")
ax.set_ylabel("Mean Hours Users Spends on the Website")

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM