在Flask中绘制透视表图表失败,请求代码问题排查
Fixing Flask Matplotlib Plot Not Displaying Issue
Let's break down what's going wrong with your code and fix it step by step:
Key Problems in Your Current Code
- Pandas Plot Creates Separate Axes: When you call
Pivotcountg.plot.bar(), pandas generates its ownAxesobject by default, which doesn't connect to thefigandaxisyou created manually. Your attempt to doaxis.plot(Pivotcountp)is invalid becausePivotcountpis anAxesinstance, not the data you want to plot. - Mismatched Plotting Context: You're trying to combine manual matplotlib figure setup with pandas' plot wrapper incorrectly, leading to the figure not being properly populated for Flask to render.
Corrected Code
First, make sure you have all necessary imports at the top of your file:
from io import BytesIO from flask import Response from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg import pandas as pd
Then update your create_figure and route functions:
@main_blueprint.route('/plot.png') def plot_png(): fig = create_figure() output = BytesIO() # Use FigureCanvasAgg for reliable PNG rendering FigureCanvasAgg(fig).print_png(output) return Response(output.getvalue(), mimetype='image/png') def create_figure(): fig = Figure() axis = fig.add_subplot(1, 1, 1) # Load data (consider using relative paths for portability) data = pd.read_excel('C:/Users/Ahmed Mustafa/FlaskProject/app/templates/sample.xlsx', sheet_name=0) data.set_index(['TicketNumber'], inplace=True) data.index.name = None # Your pivot table logic remains unchanged Pivotcountg = data.groupby("NewGroup").agg({"NewStatus": "nunique"}).reset_index() # Plot directly onto the pre-created axis using pandas plot # Specify ax=axis to bind the plot to our figure's axis Pivotcountg.plot.bar(x='NewGroup', y='NewStatus', ax=axis) # Optional: Customize plot for better readability axis.set_xlabel('Group') axis.set_ylabel('Unique Status Count') axis.set_title('Unique Statuses per Group') return fig
What Changed?
- Bound Pandas Plot to Your Axis: By adding
ax=axistoPivotcountg.plot.bar(), we tell pandas to draw the bar chart on the exact axis we created for ourfigobject, instead of creating a new, unconnected figure. - Removed Invalid
axis.plot(Pivotcountp): This line was trying to plot an Axes object, which doesn't make sense and caused errors. - Used
FigureCanvasAgg: Explicitly using the Agg backend ensures consistent PNG rendering for Flask responses. - Added Optional Customization: Tweaking labels and titles makes your plot more informative.
Additional Tips
- Use Relative Paths: Instead of hardcoding
C:/Users/Ahmed Mustafa/..., use a relative path likeapp/templates/sample.xlsx(adjust based on your project structure) to make your app portable across environments. - Check File Permissions: Ensure your Flask app has read access to the Excel file.
- Debugging: If it still doesn't work, add print statements to verify that
Pivotcountghas the expected data, and check your Flask server logs for any error messages.
内容的提问来源于stack exchange,提问作者Ahmed M.
相关产品推荐
相关产品推荐

