You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

  1. Pandas Plot Creates Separate Axes: When you call Pivotcountg.plot.bar(), pandas generates its own Axes object by default, which doesn't connect to the fig and axis you created manually. Your attempt to do axis.plot(Pivotcountp) is invalid because Pivotcountp is an Axes instance, not the data you want to plot.
  2. 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=axis to Pivotcountg.plot.bar(), we tell pandas to draw the bar chart on the exact axis we created for our fig object, 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 like app/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 Pivotcountg has the expected data, and check your Flask server logs for any error messages.

内容的提问来源于stack exchange,提问作者Ahmed M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 08:27:33