Update Trace with Button Click using Python JQuery

My goal: When a button is clicked by the user, it will display a plotly plot with a random trace from data based on a database query. For every additional click of the button, the current trace will be replaced with the new random trace.

I have successfully coded the button and plot to work with the first click of the button. However, any additional click adds the new trace to the plot instead of replacing the current trace. ie. After the second click, the plot has two traces. After the third click, the plot has three traces.

I’ve spent a couple days reading documentation/forums looking for an answer. I did find the Plotly.newPlot for Javascript, but couldn’t find anything comparable for Python. It’s possible I’ve just missed something. Is there an easy way to get the plot to recreate with just the new data? Any help would be greatly appreciated.

Here is my relevant code for the necessary files.


import culture.functions as Functions
from culture.models import Names    

@app.route('/names/', methods=['GET', 'POST'])
def names():
return render_template(names_main.html')

@app.route('/random-name/', methods=['POST'])
def random_name():
years_list = [] #x-axis
count_list = [] #y-axis
rand_row = Names.query.order_by(func.rand()).first()
rand_name = rand_row.name
chosen_name = Names.query.filter_by(name=rand_name)
all_rows = chosen_name.order_by(Names.count.desc())
year_histogram = Functions.names_histogram(all_rows, years_list, count_list)

return jsonify({'data': render_template('random_name.html', 
	rand_name=rand_name ,year_histogram=year_histogram)})


<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>

<div id="random-name">
    <h2>Choose a Random Name</h2>
    <button id="btn">Random Name Generator</button>
    <div id="response"></div>

<script src="{{ url_for('static', filename='js/jquery-3.3.1.js') }}"></script>
<script src="{{ url_for('static', filename='js/random-name.js') }}"></script>


<h3>{{ rand_name }}</h3>
<div class="graph" id="year_histogram">
        var graphs = {{year_histogram | safe}};


            url: '/random-name/',
            type: "POST",
        success: function(resp){

Hi @dustinmwest,

What happens when you replace Plotly.plot with Plotly.newPlot in random_name.html? It looks like you’re doing the plotly work in JavaScript, so this might be what you need.


Hi @jmmease,

When I try that, the plot doesn’t show up even after the first click. Thanks for the suggestion.

I did find a solution. In my random_name.js file, I changed




It’s clear now that append would add to whatever is currently there instead of replacing it.