如何設定條形寬度以匹配指定的天數?
我想要 4 個酒吧,每個月的每周一個。根據月份的不同,一周中的天數也不同。以下是我計算每周天數的方法:
from calendar import monthrange
def weekly_breakdown(year=2021, month=11):
total_days = monthrange(year, month)[1]
if total_days % 4 == 0: # 28 / 4 = 7
days_per_week = (7, 7, 7, 7)
elif total_days % 4 == 2: # 30 / 4 = 7.5
days_per_week = (8, 7, 8, 7)
elif total_days % 4 == 3: # 31 / 4 = 7.75
days_per_week = (8, 8, 8, 7)
# days_per_week = 'Week 1', 'Week 2', 'Week 3', 'Week 4'
return days_per_week
這是我的腳本中實際創建情節的部分。在此示例中,我使用 2021 年 11 月(30 天),因此我希望第一個條形寬度跨度01-08(8 天),第二個條形跨度09-15(7 天),第三個條形跨度16-23(8 天),以及要跨越的最后一個柱線24-30(7 天)。
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, DayLocator
# Generate data for bars.
df1 = pd.DataFrame(
[100, 1650, 2000, 3500],
index=['Week 1', 'Week 2', 'Week 3', 'Week 4'],
columns=['Amount']
)
df2 = pd.DataFrame(
[750, 1500, 2250, 3000],
index=['Week 1', 'Week 2', 'Week 3', 'Week 4'],
columns=['Amount']
)
# Generate line data.
days = pd.date_range(start="2021-11-01", end="2021-11-30").to_pydatetime().tolist()
daily_df = pd.DataFrame(
list(range(100, 3100, 100)),
index=days,
columns=['Cumulative']
)
fig, ax1 = plt.subplots(figsize=(8, 6), nrows=1, ncols=1)
# Share x-axis between bar and line plot.
ax2 = ax1.twiny()
df1['Amount'].plot(kind='bar', ax=ax1, color='red')
df2['Amount'].plot(kind='bar', ax=ax1, color='white', edgecolor='black', alpha=0.5)
daily_df['Cumulative'].plot(x='Adjusted Date', kind='line', ax=ax2, marker='o')
ax1.xaxis.tick_bottom()
ax1.tick_params(axis='x', rotation=0, length=0, pad=30)
ax1.set_ylabel('Dollars')
ax2.xaxis.tick_bottom()
ax2.tick_params(axis='x', which='major', length=3)
ax2.tick_params(axis='x', which='minor', length=3)
ax2.set_xlim([daily_df.index[0], daily_df.index[-1]])
ax2.xaxis.set_major_locator(DayLocator(interval=1))
ax2.xaxis.set_major_formatter(DateFormatter("%d"))

額外問題:我在哪里可以找到有關如何使用df.plot(kind='')? 我在沒有運氣的情況下搜索了 matplotlib 檔案。
uj5u.com熱心網友回復:
似乎來自 pandaswidth的df.plot('kind'=bar)函式的引數只接受單個值而不是寬度串列。但是,您可以bar直接使用matplolib 中的函式來實作您想要的。它允許您將寬度串列傳遞給函式。
您可以在下面找到代碼:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, DayLocator
import numpy as np
# Generate data for bars.
df1 = pd.DataFrame(
[100, 1650, 2000, 3500],
index=['Week 1', 'Week 2', 'Week 3', 'Week 4'],
columns=['Amount']
)
df2 = pd.DataFrame(
[750, 1500, 2250, 3000],
index=['Week 1', 'Week 2', 'Week 3', 'Week 4'],
columns=['Amount']
)
# Generate line data.
days = pd.date_range(start="2021-11-01", end="2021-11-30").to_pydatetime().tolist()
daily_df = pd.DataFrame(
list(range(100, 3100, 100)),
index=days,
columns=['Cumulative']
)
fig, ax1 = plt.subplots(figsize=(8, 6), nrows=1, ncols=1)
# Share x-axis between bar and line plot.
ax2 = ax1.twiny()
days_per_week=weekly_breakdown(2021,11)
N_days=np.sum(days_per_week)
widths=np.array(days_per_week)-1
index_bars=[1 sum(widths[0:i] 1) for i in range(len(widths))]
ax1.bar(index_bars,df1['Amount'],color='red', width=widths,align='edge')
ax1.bar(index_bars,df2['Amount'],color='white',edgecolor='black', alpha=0.5,width=widths,align='edge')
ax1.plot(np.arange(N_days) 1,daily_df['Cumulative'],marker='o')
ax1.set_xlim([1,N_days])
ax1.set_xticks(np.arange(N_days) 1)
ax2.xaxis.tick_bottom()
ax2.tick_params(axis='x', rotation=0, length=0, pad=30)
ax2.set_xticks([1./(len(df1.index))*i (1./(2*len(df1.index))) for i in range(len(df1.index))])
ax2.set_xticklabels(df1.index)
輸出給出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374582.html
標籤:Python 蟒蛇-3.x 熊猫 matplotlib
