Matplotlib: добавьте цветовую легенду к точечной диаграмме - PullRequest
0 голосов
/ 13 февраля 2020

Иметь таблицу в виде:

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

Точный график, где каждый цвет отличается от страны

enter image description here

Нужно: я хочу сделать большие круги и добавить легенду справа, когда для каждой страны будет разный цвет. Как?

1 Ответ

2 голосов
/ 13 февраля 2020

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

enter image description here

Вы можете добиться аналогичного результата с другим синтаксисом с 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")

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...