如何使用matplotblib调整每个子批次的大小

2024-05-11 03:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建3X5的子地块,但地块又窄又高。我想让情节变得更宽、更短

如何调整子批大小

这是密码

fig, ax = plt.subplots(3,5, figsize=(15,15))
counter = 0
for i in range(3):
    for j in range(5):
        ax[i][j].plot(bars_pivot_df['date'],bars_pivot_df[unique_metro_regions[counter]], c ='red', label = 'DMA')
        ax[i][j].plot(bars_pivot_df['date'],bars_pivot_df['Entire Geography'], c ='blue', label = 'statewide')
        ax[i][j].set_title(unique_metro_regions[counter]) 
        l = ax[i][j].fill_between(bars_pivot_df['date'], bars_pivot_df[unique_metro_regions[counter]])
#         plt.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9)
        counter = counter + 1
plt.show()

我尝试过使用子地块调整方法,但我不确定它是如何工作的

这就是我当前的情节- enter image description here


1条回答
网友
1楼 · 发布于 2024-05-11 03:26:10

如果宽度太窄,则应扩展图形区域。您还可以使用MonthLocator() DateFormatter()。接下来,图之间的间隔由subplots_adjust()控制。最后,使用label_outer()调整外部x、y轴的显示

import pandas as pd
import numpy as np
import random
date_rng = pd.date_range('2018-01-01','2019-12-31', freq='1D')
val = np.random.randint(0,500,(730,))
country = ['country_'+str(x) for x in range(15)]
df = pd.DataFrame({'date':pd.to_datetime(date_rng), 'value':val})
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots(3,5, figsize=(20,15))
fig.subplots_adjust(wspace=0.3, hspace=0.1)

counter = 0
for i in range(3):
    for j in range(5):
        ax[i][j].plot(df['date'], df['value'], c ='blue')
        ax[i][j].set_title(country[counter]) 
        l = ax[i][j].fill_between(df['date'], df['value'])

        ax[i][j].xaxis.set_major_locator(mdates.MonthLocator(bymonth=None, interval=6, tz=None))
        ax[i][j].xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
        ax[i][j].label_outer()
        ax[i][j].tick_params(axis='x', labelrotation=45)
        counter = counter + 1

plt.show()

enter image description here

相关问题 更多 >