Python多图表合并PDF页面问题:将4张图表合并为2页
Solution: Combine Charts into 2 Pages (One Company Per Page)
Got it, let's get this sorted! The issue right now is that you're creating a separate figure for each individual chart, and each pdf.savefig() call adds a new page. To put two charts per page (one company's financials + stock price), we'll use matplotlib's subplot system to stack both charts onto a single figure, then save that figure once per company.
Here's the revised code with explanations:
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter import numpy as np from matplotlib.backends.backend_pdf import PdfPages with PdfPages('multipage_pdf.pdf') as pdf: # ---------------------- FIRST COMPANY: Page 1 ---------------------- # Create a single figure with 2 rows, 1 column of subplots fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 10)) # Adjust figsize as needed # --- Top subplot: Financial bar chart --- index = np.arange(n_groups) bar_width = 0.35 opacity = 0.8 rects1 = ax1.bar(index, z, bar_width, alpha=opacity, color='b', label='Zysk_(strata)_netto') rects2 = ax1.bar(index + bar_width, v, bar_width, alpha=opacity, color='g', label='Zysk_(strata)_działal_oper') rects3 = ax1.bar(index + bar_width*2, b, bar_width, alpha=opacity, color='y', label='EBITDA') ax1.set_xlabel('Kwartaly') ax1.set_ylabel('PLN') ax1.set_title(companys_to_chart[0]) ax1.set_xticks(index + bar_width, x) ax1.legend() ax1.grid(True) # --- Bottom subplot: Stock price + WIG chart --- x_stock = company['Date'] y_stock = company['Close'] x_wig = WIG['Date'] y_wig = WIG['Close'] ax2.plot(x_stock, y_stock, label='Price') ax2.set_ylabel("PLN") ax2.set_xlabel("Date") ax2.grid(True) # Twin axis for WIG ax2_twin = ax2.twinx() ax2_twin.plot(x_wig, y_wig, 'y-', label='WIG') ax2_twin.set_ylabel('Points', size=10) # Format dates myFmt = DateFormatter("%d-%m-%y") ax2.xaxis.set_major_formatter(myFmt) fig.autofmt_xdate() # Combine legends for the bottom chart lines1, labels1 = ax2.get_legend_handles_labels() lines2, labels2 = ax2_twin.get_legend_handles_labels() ax2.legend(lines1 + lines2, labels1 + labels2, bbox_to_anchor=(0.85, 0.35)) ax2.set_title(name_of_company) # Adjust layout to prevent overlapping plt.tight_layout() # Save the entire figure (both charts) as one page pdf.savefig(fig) plt.close() # ---------------------- SECOND COMPANY: Page 2 ---------------------- # Repeat the same structure for the second company fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 10)) # --- Top subplot: Financial bar chart --- index = np.arange(n_groups) bar_width = 0.35 opacity = 0.8 rects1 = ax1.bar(index, z_1, bar_width, alpha=opacity, color='b', label='Zysk_(strata)_netto') rects2 = ax1.bar(index + bar_width, v_1, bar_width, alpha=opacity, color='g', label='Zysk_(strata)_działal_oper') rects3 = ax1.bar(index + bar_width*2, b_1, bar_width, alpha=opacity, color='y', label='EBITDA') ax1.set_xlabel('Kwartaly') ax1.set_ylabel('PLN') ax1.set_title(companys_to_chart[1]) ax1.set_xticks(index + bar_width, x_1) # Fixed: use x_1 instead of x here ax1.legend() ax1.grid(True) # --- Bottom subplot: Stock price + WIG chart --- x_stock = company_2['Date'] # Fixed: use company_2's data here (original code used company) y_stock = company_2['Close'] x_wig = WIG['Date'] y_wig = WIG['Close'] ax2.plot(x_stock, y_stock, label='Price') ax2.set_ylabel("PLN") ax2.set_xlabel("Date") ax2.grid(True) ax2_twin = ax2.twinx() ax2_twin.plot(x_wig, y_wig, 'y-', label='WIG') ax2_twin.set_ylabel('Points', size=10) myFmt = DateFormatter("%d-%m-%y") ax2.xaxis.set_major_formatter(myFmt) fig.autofmt_xdate() lines1, labels1 = ax2.get_legend_handles_labels() lines2, labels2 = ax2_twin.get_legend_handles_labels() ax2.legend(lines1 + lines2, labels1 + labels2, bbox_to_anchor=(0.85, 0.35)) ax2.set_title(name_of_company_1) plt.tight_layout() pdf.savefig(fig) plt.close()
Key Changes Made:
- Single figure per company: We use
plt.subplots(2, 1)to create a figure with two stacked subplots (top = financial chart, bottom = stock chart). - Fixed minor bugs: Corrected references to
company_2data in the second company's stock chart, and usedx_1for the second company's quarter labels. - Improved legend handling: Combined legends for the twin-axis stock/WIG chart to avoid overlapping issues.
- Layout adjustment:
plt.tight_layout()ensures all labels and titles fit without overlapping.
Now your PDF will have exactly 2 pages—each page containing both charts for one company!
内容的提问来源于stack exchange,提问作者Tmiskiewicz
相关产品推荐
相关产品推荐

