使用数据框散点图中的图例

问题描述 投票:0回答:1

图例中仅显示第一个数据名称,即“Manchester City”。

import pandas as pd 
import matplotlib.pyplot as plt
df1=pd.read_csv(r'F:\anoch\IPproject\FSTS\teams.csv')
df1.plot(kind='scatter',x='GOALS/90min', y='xG',c=['red', 'green', 'blue', 'yellow','black','purple','aquamarine','grey','tan','khaki'])
plt.legend(['Manchester City','Bayern Muchen','Real Madrid','Internazionale','Liverpool','Arsenal','FC Barcelona','Atletico Madrid','PSG','RB Leipzig'],bbox_to_anchor=(-0.1, 0.75))
plt.show()

我不是专家。我正在为一个学校项目做这个。你们的任何帮助都会很棒。

python pandas legend scatter-plot
1个回答
0
投票

我认为如果你只使用 matplotlib 而不是 pandas 会更容易,因为它给你更多的控制权,同时使用 legend() 这种方式并不能确保它获得正确的颜色/团队名称:

import pandas as pd
import matplotlib.pyplot as plt

# Sample data as I do not have your csv
df1 = pd.DataFrame({
    "GOALS/90min": [1, 2, 3],
    "xG": [1, 2, 3],
    "team": ['Manchester City', 'Bayern Muchen', 'Real Madrid']
})

# this or add a column with df["colors"] = [...] or use some other method
colors = {'Manchester City': 'red', 
          'Bayern Muchen': 'green', 
          'Real Madrid': 'blue'}


for team in df1.team.unique():
    data = df1.loc[df1.team==team]
    plt.scatter(data['GOALS/90min'], data['xG'], color=colors[team], label=team)

plt.legend()
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.