これは以前は正常に機能していましたが、どういうわけか機能しなくなりました(何かを誤って変更したに違いありませんが、問題を見つけることができません)。
日付ごとに3つのバーのセットと、そのうちの1つの累積値を示す線をプロットしています。ただし、適切にプロットされているのは、いずれか(棒または線)のみです。バーのコードを最後に残した場合、バーのみがプロットされます。行のコードを最後に残した場合、行のみがプロットされます。
fig, ax = plt.subplots(figsize = (15,8))
df.groupby("date")["result"].sum().cumsum().plot(
ax=ax,
marker='D',
lw=2,
color="purple")
df.groupby("date")[selected_columns].sum().plot(
ax=ax,
kind="bar",
color=["blue", "red", "gold"])
ax.legend(["LINE", "X", "Y", "Z"])
助けに感謝します!
Pandasは、x軸をカテゴリとして棒グラフを描画するため、内部に番号を付けて0, 1, 2, ...
からラベルを設定します。折れ線グラフは、日付をx軸として使用します。それらを組み合わせるには、両方がカテゴリである必要があります。最も簡単な方法は、折れ線グラフからインデックスを削除することです。折れ線グラフが最初に描画されていることを確認し、棒グラフでラベルを正しく設定できるようにします。
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'date': pd.date_range('20210101', periods=10),
'earnings': np.random.randint(100, 600, 10),
'costs': np.random.randint(0, 200, 10)})
df['result'] = df['earnings'] - df['costs']
fig, ax = plt.subplots(figsize=(15, 8))
df.groupby("date")["result"].sum().cumsum().reset_index(drop=True).plot(
ax=ax,
marker='D',
lw=2,
color="purple")
df.groupby("date")[['earnings', 'costs', 'result']].sum().plot(
ax=ax,
kind="bar",
rot=0,
width=0.8,
color=["blue", "red", "gold"])
ax.legend(['Cumul.result', 'earnings', 'costs', 'result'])
# shorten the tick labels to only the date
ax.set_xticklabels([tick.get_text()[:10] for tick in ax.get_xticklabels()])
ax.set_ylim(ymin=0) # bar plots are nicer when bars start at zero
plt.tight_layout()
plt.show()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加