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.
views.py
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)})
names_main.html
<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>
</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>
random_name.html
<h3>{{ rand_name }}</h3>
<div class="graph" id="year_histogram">
<script>
var graphs = {{year_histogram | safe}};
Plotly.plot('year_histogram',graphs,{});
</script>
</div>
random_name.js
$('button#btn').click(function(){
$.ajax({
url: '/random-name/',
type: "POST",
success: function(resp){
$('div#response').append(resp.data);
}
});
});