在Flask中绘制数据透视表

2024-10-01 22:35:35 发布

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

我已经创建了透视表,并尝试在Flask中绘制它,如下所示:

def create_figure():
  fig = Figure()
  axis = fig.add_subplot(1, 1, 1)
  data = pd.read_excel('C:/Users/Ahmed Mustafa/FlaskProject/app/templates/sample.xlsx',0)
  data.set_index(['TicketNumber'], inplace=True)
  data.index.name=None
  tickets = data.loc[data.Status=='Closed']
  Pivotcountg = data.groupby("NewGroup")
  Pivotcountg = Pivotcountg.agg({"NewStatus": "nunique"})
  Pivotcountg = Pivotcountg.reset_index()
  Pivotcount = data.groupby('NewGroup').count()
  Pivotcountp = Pivotcountg.plot.bar()

但当我试着把它画成如下图:

@main_blueprint.route('/plot.png')
  def plot_png():
    fig = create_figure()
    output = io.BytesIO()
    FigureCanvas(fig).print_png(output)
    return Response(output.getvalue(), mimetype='image/png')

  def create_figure():
   fig = Figure()
   axis = fig.add_subplot(1, 1, 1)
   data = pd.read_excel('C:/Users/Ahmed Mustafa/FlaskProject/app/templates/sample.xlsx',0)
   data.set_index(['TicketNumber'], inplace=True)
   data.index.name=None
   tickets = data.loc[data.Status=='Closed']
   Pivotcountg = data.groupby("NewGroup")
   Pivotcountg = Pivotcountg.agg({"NewStatus": "nunique"})
   Pivotcountg = Pivotcountg.reset_index()
   Pivotcount = data.groupby('NewGroup').count()
   Pivotcountp = Pivotcountg.plot.bar()
   axis.plot(Pivotcountp)
   return fig

它不起作用

我在html文件中包含了以下行:

<img src="/plot.png" alt="my plot">

Tags: outputdataindexplotpngdefcreatefig
1条回答
网友
1楼 · 发布于 2024-10-01 22:35:35

我能够解决这个问题;下面是对.py文件的修改

@main_blueprint.route('/plot.png')
def plot_png():
fig = create_figure()
output = io.BytesIO()
FigureCanvas(fig).print_png(output)
return Response(output.getvalue(), mimetype='image/png')

def create_figure():
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
data = pd.read_excel('C:/Users/Ahmed 
Mustafa/FlaskProject/app/templates/Repo/RAWDATA/sample.xlsx',0)
data.set_index(['TicketNumber'], inplace=False)
data.index.name=None
tickets = data.loc[data.Status=='Closed']
Pivotcountg = data.groupby("NewGroup")
Pivotcountg = Pivotcountg.agg({"NewStatus": "nunique"})
Pivotcountg = Pivotcountg.reset_index()
Pivotcount = data.groupby('NewGroup').count()
Pivotcountp = Pivotcountg.plot.bar()
xs = Pivotcountg.iloc[:, 0]
ys = Pivotcountg.iloc[:, 1]
xxx = np.arange(len(xs))  # the label locations
axis.set_title('Referrals between Groups')
axis.set_xlabel('Referred To Groups')
axis.set_ylabel('Number of Referrals')
axis.set_xticks(xxx)
axis.set_xticklabels(xs, rotation=45)
axis.tight_layout()
axis.legend()
axis.plot(xs, ys)
fig.tight_layout()
return fig

此外,我还可以通过在HTML页面中包含以下内容来显示结果图:

<img src="/plot.png" alt="my plot">

相关问题 更多 >

    热门问题