为每个plt.step线条分配不同的颜色。

huangapple go评论53阅读模式
英文:

Assign different color to each plt.step line

问题

我已经让它工作了,只有两个问题:

  1. 由于每次绘制线条时都为每个队伍进行迭代,因此会绘制第4条(紫色)线条,尽管只有3支队伍。这条线是为每次迭代(每支队伍)绘制的。但为什么呢?

  2. 线条是从x = 0的起点绘制的,因此与点(已正确绘制)不对齐。线条应该从x = 1的起点开始绘制,根据它们的Game_week值。

输出:

为每个plt.step线条分配不同的颜色。

我错过了什么?

以下是示例代码:

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

df = pd.DataFrame([['Team1', 1, 1],
                   ['Team1', 2, 2],
                   ['Team1', 1, 3],
                   ['Team1', 5, 4],
                   ['Team1', 1, 5],
                   ['Team2', 2, 1],
                   ['Team2', 3, 2],
                   ['Team2', 4, 3],
                   ['Team2', 4, 4],
                   ['Team2', 3, 5],
                   ['Team3', 3, 1],
                   ['Team3', 4, 2],
                   ['Team3', 3, 3],
                   ['Team3', 2, 4],
                   ['Team3', 2, 5]
                   ], columns=['Team', 'Position', 'Game_week'])

positions = df['Position']
weeks = df['Game_week']
teams = df['Team'].unique()
print(teams)

# 坐标:
y = positions
x = weeks
print(y)
print(x)

fig, ax = plt.subplots()

# 标签:
plt.xlabel('Game weeks')
plt.ylabel('Positions')
plt.xlim(-0.2, 5.2)
plt.ylim(0.8, 5.2)

# 反转y轴:
plt.gca().invert_yaxis()

# x, y刻度:
xi = list(np.unique(x))
yi = list(np.unique(y))
plt.xticks(xi)
plt.yticks(yi)

# 队伍的颜色:
colors = {'Team1': 'tab:red', 'Team2': 'tab:blue', 'Team3': 'blue'}

# 点:
plt.scatter(x, y, s=45, c=df['Team'].map(colors), zorder=2)

# 点之间的线:
for i, (team, l) in enumerate(df.groupby('Team', sort=False)):
    plt.step(list(zip(l['Game_week'], l['Position'])),
             '-',
             color=colors[team],
             linewidth=8,
             alpha=0.2, zorder=1)
    print('step:', i, '; team:', [team])
    print(l)

plt.show()
plt.close()

谢谢!

英文:

I have a code which draws lines for the teams according to their tournament position in each game week.
Pretty much I managed to make it work, except 2 things:

  1. For some reason a 4th (violet) line is drawn (teams are only 3) which goes from the top to the bottom throughout each game week. As I found out this line is drawn for every iteration (for each team) when plotting the lines. But why?
  2. Lines are drawn from x = 0 starting point, thus not aligning with the points (which are drawn correctly). Lines should be drawn from x = 1 starting point as well (according to their Game_week value).
    Output:

为每个plt.step线条分配不同的颜色。

What have I missed?

Example of the code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame([['Team1', 1, 1],
['Team1', 2, 2],
['Team1', 1, 3],
['Team1', 5, 4],
['Team1', 1, 5],
['Team2', 2, 1],
['Team2', 3, 2],
['Team2', 4, 3],
['Team2', 4, 4],
['Team2', 3, 5],
['Team3', 3, 1],
['Team3', 4, 2],
['Team3', 3, 3],
['Team3', 2, 4],
['Team3', 2, 5]
], columns=['Team', 'Position', 'Game_week'])
positions = df['Position']
weeks = df['Game_week']
teams = df['Team'].unique()
print(teams)
# Coordinates:
y = positions
x = weeks
print(y)
print(x)
fig, ax = plt.subplots()
# Labels:
plt.xlabel('Game weeks')
plt.ylabel('Positions')
plt.xlim(-0.2, 5.2)
plt.ylim(0.8, 5.2)
# Inverting the y-axis:
plt.gca().invert_yaxis()
# x, y ticks:
xi = list(np.unique(x))
yi = list(np.unique(y))
plt.xticks(xi)
plt.yticks(yi)
# Colors for teams:
colors = {'Team1': 'tab:red', 'Team2': 'tab:blue', 'Team3': 'blue'}
# Points:
plt.scatter(x, y, s=45, c=df['Team'].map(colors), zorder=2)
# Lines between points:
for i, (team, l) in enumerate(df.groupby('Team', sort=False)):
plt.step(list(zip(l['Game_week'], l['Position'])),
'-',
color=colors[team],
linewidth=8,
alpha=0.2, zorder=1)
print('step:', i, '; team:', [team])
print(l)
plt.show()
plt.close()

Thank you!

答案1

得分: 2

问题出在plt.step(),你正在使用zip。根据文档这里,你只需要提供x和y的值。将该行更新如下...

for i, (team, l) in enumerate(df.groupby('Team', sort=False)):
    plt.step(l['Game_week'], l['Position'], ## 不需要zip
             '-',
             color=colors[team],
             linewidth=8,
             alpha=0.2, zorder=1)

...将给你这个图。是否满足你的需求?你可能想要更改xlim,也许从0.8开始。

为每个plt.step线条分配不同的颜色。

英文:

The issues is with the plt.step(), where you are using zip. As per documentation here, you just need to give the x and y values. Updating that line as below...

for i, (team, l) in enumerate(df.groupby('Team', sort=False)):
plt.step(l['Game_week'], l['Position'], ## No zip
'-',
color=colors[team],
linewidth=8,
alpha=0.2, zorder=1)

.. will give you this plot. Does this meet your needs? You may want to change xlim to start at 0.8 perhaps.

为每个plt.step线条分配不同的颜色。

huangapple
  • 本文由 发表于 2023年6月18日 23:27:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定