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

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

Assign different color to each plt.step line

问题

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

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

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

输出:

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

我错过了什么?

以下是示例代码:

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. df = pd.DataFrame([['Team1', 1, 1],
  5. ['Team1', 2, 2],
  6. ['Team1', 1, 3],
  7. ['Team1', 5, 4],
  8. ['Team1', 1, 5],
  9. ['Team2', 2, 1],
  10. ['Team2', 3, 2],
  11. ['Team2', 4, 3],
  12. ['Team2', 4, 4],
  13. ['Team2', 3, 5],
  14. ['Team3', 3, 1],
  15. ['Team3', 4, 2],
  16. ['Team3', 3, 3],
  17. ['Team3', 2, 4],
  18. ['Team3', 2, 5]
  19. ], columns=['Team', 'Position', 'Game_week'])
  20. positions = df['Position']
  21. weeks = df['Game_week']
  22. teams = df['Team'].unique()
  23. print(teams)
  24. # 坐标:
  25. y = positions
  26. x = weeks
  27. print(y)
  28. print(x)
  29. fig, ax = plt.subplots()
  30. # 标签:
  31. plt.xlabel('Game weeks')
  32. plt.ylabel('Positions')
  33. plt.xlim(-0.2, 5.2)
  34. plt.ylim(0.8, 5.2)
  35. # 反转y轴:
  36. plt.gca().invert_yaxis()
  37. # x, y刻度:
  38. xi = list(np.unique(x))
  39. yi = list(np.unique(y))
  40. plt.xticks(xi)
  41. plt.yticks(yi)
  42. # 队伍的颜色:
  43. colors = {'Team1': 'tab:red', 'Team2': 'tab:blue', 'Team3': 'blue'}
  44. # 点:
  45. plt.scatter(x, y, s=45, c=df['Team'].map(colors), zorder=2)
  46. # 点之间的线:
  47. for i, (team, l) in enumerate(df.groupby('Team', sort=False)):
  48. plt.step(list(zip(l['Game_week'], l['Position'])),
  49. '-',
  50. color=colors[team],
  51. linewidth=8,
  52. alpha=0.2, zorder=1)
  53. print('step:', i, '; team:', [team])
  54. print(l)
  55. plt.show()
  56. 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:

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. df = pd.DataFrame([['Team1', 1, 1],
  5. ['Team1', 2, 2],
  6. ['Team1', 1, 3],
  7. ['Team1', 5, 4],
  8. ['Team1', 1, 5],
  9. ['Team2', 2, 1],
  10. ['Team2', 3, 2],
  11. ['Team2', 4, 3],
  12. ['Team2', 4, 4],
  13. ['Team2', 3, 5],
  14. ['Team3', 3, 1],
  15. ['Team3', 4, 2],
  16. ['Team3', 3, 3],
  17. ['Team3', 2, 4],
  18. ['Team3', 2, 5]
  19. ], columns=['Team', 'Position', 'Game_week'])
  20. positions = df['Position']
  21. weeks = df['Game_week']
  22. teams = df['Team'].unique()
  23. print(teams)
  24. # Coordinates:
  25. y = positions
  26. x = weeks
  27. print(y)
  28. print(x)
  29. fig, ax = plt.subplots()
  30. # Labels:
  31. plt.xlabel('Game weeks')
  32. plt.ylabel('Positions')
  33. plt.xlim(-0.2, 5.2)
  34. plt.ylim(0.8, 5.2)
  35. # Inverting the y-axis:
  36. plt.gca().invert_yaxis()
  37. # x, y ticks:
  38. xi = list(np.unique(x))
  39. yi = list(np.unique(y))
  40. plt.xticks(xi)
  41. plt.yticks(yi)
  42. # Colors for teams:
  43. colors = {'Team1': 'tab:red', 'Team2': 'tab:blue', 'Team3': 'blue'}
  44. # Points:
  45. plt.scatter(x, y, s=45, c=df['Team'].map(colors), zorder=2)
  46. # Lines between points:
  47. for i, (team, l) in enumerate(df.groupby('Team', sort=False)):
  48. plt.step(list(zip(l['Game_week'], l['Position'])),
  49. '-',
  50. color=colors[team],
  51. linewidth=8,
  52. alpha=0.2, zorder=1)
  53. print('step:', i, '; team:', [team])
  54. print(l)
  55. plt.show()
  56. plt.close()

Thank you!

答案1

得分: 2

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

  1. for i, (team, l) in enumerate(df.groupby('Team', sort=False)):
  2. plt.step(l['Game_week'], l['Position'], ## 不需要zip
  3. '-',
  4. color=colors[team],
  5. linewidth=8,
  6. 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...

  1. for i, (team, l) in enumerate(df.groupby('Team', sort=False)):
  2. plt.step(l['Game_week'], l['Position'], ## No zip
  3. '-',
  4. color=colors[team],
  5. linewidth=8,
  6. 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:

确定