-1

I need some help, the situation is I m able to return the new CSV file but unable to return the plot graph to another page, and I did separate the return under different scenarios. Does anyone can point out what should I do to my code? or perhaps give me some tips, Thanks in advance!

app.py

@app.route('/transform', methods=["POST"])
def transform_view():
    if request.method == 'POST':
        if request.files['data_file']:
            f = request.files['data_file']
            if not f:
                return "No file"
    
            
            stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
            csv_input = csv.reader(stream)
            stream.seek(0)
            result = stream.read()
            df = pd.read_csv(StringIO(result), usecols=[1])
            
            #extract month value
            df2 = pd.read_csv(StringIO(result))
            matrix2 = df2[df2.columns[0]].to_numpy()
            list1 = matrix2.tolist()
             
            # load the model from disk
            model = load_model('model.h5')
            dataset = df.values
            dataset = dataset.astype('float32')
            scaler = MinMaxScaler(feature_range=(0, 1))
            dataset = scaler.fit_transform(dataset)
            look_back = 1
            dataset_look = create_dataset(dataset, look_back)
            dataset_look = np.reshape(dataset_look, (dataset_look.shape[0], 1, dataset_look.shape[1]))
            predict = model.predict(dataset_look)
            transform = scaler.inverse_transform(predict)
    
            X_FUTURE = 12
            transform = np.array([])
            last = dataset[-1]
            for i in range(X_FUTURE):
                curr_prediction = model.predict(np.array([last]).reshape(1, look_back, 1))
                last = np.concatenate([last[1:], curr_prediction.reshape(-1)])
                transform = np.concatenate([transform, curr_prediction[0]])
          
            transform = scaler.inverse_transform([transform])[0]
    
            dicts = []
            curr_date = pd.to_datetime(list1[-1])
            for i in range(X_FUTURE):
                curr_date = curr_date +  relativedelta(months=+1)
                dicts.append({'Predictions': transform[i], "Month": curr_date})
    
    
            new_data = pd.DataFrame(dicts).set_index("Month")
            ##df_predict = pd.DataFrame(transform, columns=["predicted value"])
    
                          
        
            response = make_response(new_data.to_csv(index = True, encoding='utf8'))
            response.headers["Content-Disposition"] = "attachment; filename=result.csv"
            return response
        
            labels = [
                        'JAN', 'FEB', 'MAR', 'APR',
                        'MAY', 'JUN', 'JUL', 'AUG',
                        'SEP', 'OCT', 'NOV', 'DEC'
                       ]
    
            values = [
                            967.67, 1190.89, 1079.75, 1349.19,
                            2328.91, 2504.28, 2873.83, 4764.87,
                            4349.29, 6458.30, 9907, 16297
                        ]
    
            colors = [
                            "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
                            "#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
                            "#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
            return redirect(url_for('line'))
    
    @app.route('/line')
    def line():
        line_labels=labels
        line_values=values
        return render_template('graph.html', title='Bitcoin Monthly Price in USD', max=17000, labels=line_labels, values=line_values)

1 Answer 1

0

you have to save it first to specific folder and then in frontend you can specify the image like that you pass it in url

from matplotlib import pyplot as plt
     
plt.savefig('path/plot.png')

or else you can use JavaScript to render graph to frontend you can use chart.js etc.

Sign up to request clarification or add additional context in comments.

10 Comments

Hi @Bhavya, Thanks for commenting, I did try to add plt.savefig('path/plot.png') and it actually does not work, the problem is it dint return render_template at all, and can you demo like how to plot graph using chart.js as you said ?
Hey you can refer stackoverflow.com/questions/50728328/… from here! and for chart.js you can go through official document as well as from stack overflow it self you can find your answer just try diff. methods.
I think chartjs also not work because it has to return render_template also, my problem is the second return cannot work at all
I have edited another version for you to see my problem, I cant return my return redirect(url_for('line')), Please help ~
your code is not as with proper indentation required in python see that first if condition please update the code
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.