【问题标题】:Plot with for cycle on pandas在熊猫上使用 for 循环绘图
【发布时间】:2020-06-25 05:41:45
【问题描述】:

假设我有一个带有“日期”列的 df,用于过滤我想要的冠军,并且我通过将“日期”列设置为索引来做到这一点。此外,我有一个功能可以根据需要配置所有列类型:

import pandas as pd
df = pd.DataFrame({'Date':['26-12-2018','26-12-2018','27-12-2018','27-12-2018','28-12-2018','28-12-2018'],
                   'In':['A','B','D','Z','Q','E'],
                   'Out' : ['Z', 'D', 'F', 'H', 'Z', 'A'],
                   'Score_in' : ['6', '2', '1', '0', '1', '3'], 
                   'Score_out' : ['2','3','0', '1','1','3'],
                   'Place' : ['One','Two','Four', 'Two','Two','One']})

我可以在同一个图上绘制吗 - 因为它是一个网格 - 例如:

df.groupby('In').Score_in.sum().add(df.groupby('Out').Score_out.sum())

通过将函数参数“day”作为迭代器传递给每一天的 for 循环? 我不明白有多好,比如:

for it in range(26:28:1):

    if it == day:
        ..plot_settings.. f(it)

【问题讨论】:

  • 无关:range(26:28:1) ? range(26,28,1)?或[26,27] ?
  • 你能解释一下你最后想要什么样的图表(情节)? X 天内每天的总得分,作为折线图?还有什么?
  • 我认为更多的是直方图而不是折线图。像 hexbin 格式一样可行吗?
  • 直方图是什么?您能否在问题中添加所需的输出(即使是餐巾纸背面的素描照片)?
  • 也许考虑条形图更正确,其中 x 标签上有团队,y 标签上有总分,但我想用 for 循环来做,所以我可以每天都在同一个网格上

标签: python pandas matplotlib


【解决方案1】:

这是一段代码,用于构建数据的 matplotlib 图。需要注意的是,据我所知,matplotlib 并不是最适合这种绘图的包。

import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 

df["score"] = pd.to_numeric(df["score"])
df = df.groupby(["Date", "team"]).sum()
df = df.reset_index()

fig, ax = plt.subplots()

groups = df.Date.unique()
num_groups = len(groups)

ind = np.arange(num_groups)    # the x locations for the groups
width = 0.10                   # the width of the bars

days = pd.date_range(df.Date.min(), df.Date.max(), freq = "1D")

rect_list = []
for inx, t in enumerate(df.team.unique()) :
    sub_df = df[df.team == t]
    sub_df = sub_df.set_index("Date").reindex(days)

    x_locations = ind + width * inx
    rects = ax.bar(x_locations, sub_df.score, width, bottom = 0)
    rect_list.append(rects)

ax.legend(rect_list, df.team.unique())
        
ax.set_xticks(ind + width*2)

labels = [pd.to_datetime(x).strftime("%Y-%m-%d") for x in groups]
ax.set_xticklabels(labels)

fig.show()

结果是:

如果您希望将每一天都放在一个单独的情节中,您可以执行以下操作:

import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 

df["score"] = pd.to_numeric(df["score"])
df = df.groupby(["Date", "team"]).sum()
df = df.reset_index()

days = df.Date.unique()

fig, subplots = plt.subplots(len(days), 1)

all_teams = df.team.unique()

for d, ax in zip(days, subplots):

    sub_df = df[df.Date == d]
    
    sub_df.set_index("team", inplace=True)
    sub_df = sub_df.reindex(all_teams).sort_index().fillna(value = 0)
    
    rects = ax.bar(sub_df.index, sub_df.score, width, bottom = 0)
    ax.set_title(pd.to_datetime(d).strftime("%Y-%m-%d"))

plt.show()

输出:

【讨论】:

  • 谢谢罗伊!它真的很接近我一直在寻找的东西:有没有办法在网格图上将每一天的图分开,而不是全部在同一个图上?
  • 感谢您的编辑罗伊!我有最后一个疑问:我明白你对 df["score"] 是什么意思,即 df["Score_in"] + df["Score_out"],但我怎样才能找到你命名的 df["team"] ?
  • 团队是原始的“In”和“out”(A、B、C 等)。
猜你喜欢
  • 1970-01-01
  • 2022-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2013-08-21
  • 2013-10-03
相关资源
最近更新 更多