正在将Python信息获取到Chart.JS

2024-06-01 04:23:00 发布

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

我有一个使用flask的python后端程序,我正在上传一个CSV文件,用Chart.JS创建一个图形。我对这个程序非常不熟悉,我现在有点困了。我现在正在创建一个基本图,但我不确定如何从python获取值,以便在chart.js上使用它们。当我尝试将{{dataxarray}}输入到图表上的数据时,它只是破坏了图表,没有显示任何内容,我不太确定如何解决这个问题。任何帮助都将不胜感激

Views.py

 
@app.route('/', methods=["GET", "POST"])
def index():
    data = []
    if request.method == 'POST':
        if request.files:
            uploaded_file = request.files['filename']
            filepath = os.path.join(app.config['FILE_UPLOADS'], uploaded_file.filename)
            uploaded_file.save(filepath)
            with open(filepath) as file:
                csv_file = csv.reader(file)
                for row in csv_file:
                    data.append(row)
            data = pd.DataFrame(data[1:], columns=data[0])
            if len(data.columns) >=3:
                error_msg = 'Error please select a CSV with two columns'
                return error_msg

            d_list = list(data.columns.values)

            def get_x_label():
                x_label = d_list[0]
                return x_label
            def get_y_label():
                y_label = d_list[1]
                return y_label
            def get_title():
                new_file = uploaded_file.filename.replace(".csv", "")
                return new_file
            def get_x_array():
                d_list = list(data.columns.values)
                x_label = d_list[0]
                data_x_array = np.array(data[x_label])
                return data_x_array
            def get_y_array():
                d_list = list(data.columns.values)
                y_label = d_list[1]
                data_y_array = np.array(data[y_label])
                return data_y_array

            return render_template('index.html', datayarray=get_y_array(), dataxarray=get_x_array(), dataframe=data, x_label=get_x_label(), y_label=get_y_label(), chart_title=get_title(), tables=[data.to_html(classes='data')], titles=str(data.iloc[0]), header=False, index=False, index_names=False)
    return render_template('index.html', data=data)


@app.route('/help')
def help():
    return render_template('help.html')

app.config['FILE_UPLOADS'] = "C:\\Users\\Zachary\\Documents\\VSCode_Projects\\monday_webapp\\app\\static\\file\\uploads"

Index.html

{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block body %}

<div class="background">
    <h1 style='text-align: center'>Zach's Web Application</h1>
    <br>
    <br>
    <br>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"></script>
    <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://dl.dropbox.com/s/iyrrn20zt5za9ma/styles.css"/>
    <script>
        $(document).ready(function(){
            $('table').DataTable();
            $("#form_button").on('click', function(e) {
                    e.preventDefault();
                    validateDropDown();
                });
                var ctx = document.getElementById('myChart').getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                    datasets: [{
                        label: '# of Votes',
                        data: "[12, 19, 3, 5, 2, 3]",
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                        ],
                        borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });

        } );
        function validateDropDown() {
                var ddl = document.getElementById('ddl');
                if(ddl.selectedIndex == 0 || ddl.options[ddl.selectedIndex].value == -1) {
                    alert('Please select a valid option!');
                    return false;
                }
                if(ddl.selectedIndex == 1){
                    $('#hidden_data').removeClass('hidden');
                }
                if(ddl.selectedIndex == 2){
                    $('#hidden_data').removeClass('hidden');

                }
                if(ddl.selectedIndex == 3){
                    $('#hidden_data').removeClass('hidden');

                }
                if(ddl.selectedIndex == 4){
                    $('#hidden_data').removeClass('hidden');

                }
                return true;
            }

    </script>
</div>
<div>
    <p class="lead">Select Option from dropdown window</p>
</div>
<div>
    <form id='form_id' onsubmit="return validateDropDown('ddl');">
        <select id="ddl">
            <option value="-1">----- Please Select -----</option>
            <option>Single Line Graph</option>
            <option>Multiple Line Graph</option>
            <option>Single Bar Graph</option>
            <option>Stacked Bar Graph</option>
        </select>
        <br>
        <input id='form_button' type="submit" />
    </form>
</div>
<br>
<div>
    <form id='hidden_data' class='hidden' method="POST" enctype="multipart/form-data" action="/">
        <input class='background' type="file" id="myFile" name="filename" accept=".csv">
        <input id='renderButton' type="submit">
    </form>
    </div>
</div>
<br>
<br>
<div id="div_table">
    {% for table in tables %}
            {{ table|safe }}
    {% endfor %}
    {{ error_msg }}
</div>
<div>
    <canvas id="myChart" width="100" height="100"></canvas>
</div>
<div>

{% endblock %}

Tags: dividdatagetreturnifscriptarray