为pandas散点图中的每一行添加图例标签

bbmckpt7  于 2023-05-12  发布在  其他
关注(0)|答案(1)|浏览(127)

将表设置为:

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()

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

需要:我想做一个大圆圈,并在右侧添加传奇时,每个国家将是不同的颜色。怎么做?

7eumitmz

7eumitmz1#

在matplotlib中,您可以为每个国家添加不同的分散点(即你的dataframe索引的每一层),并将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")

相关问题