Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

python - Add dropdown filter to Plotly Express Chart

I have the following code (in a flask view) displaying the average rating of different restaurants over 12 months:

@bp.route("/")
@bp.route("/index")
def index():
  ratings = {
    "restaurant_1": [3.6, 3.2, 4.1, 3.9, 4.6, 4.4, 5, 4.8, 4.2, 3.7, 4.3, 3],
    "restaurant_2": [4.7, 4, 4.1, 2.1, 2.8, 3.5, 5, 4.1, 4.2, 2, 4, 1],
    "restaurant_3": [3, 2, 1.1, 1.5, 1.7, 3, 2, 1, 1.7, 2, 1, 1.8],
    "restaurant_4": [1, 1.5, 2.1, 1.7, 1.4, 1, 1.1, 1.3, 1.3, 1.5, 2, 1.8]
  }

  basic_plot = px.line(
    x=["January", "February", "March", "April", "May", "June", "July", "August", "September",
       "October", "November", "December"],
    y=[ratings["restaurant_1"], ratings["restaurant_2"], ratings["restaurant_3"], ratings["restaurant_4"]],
    title="Brands Rating", template="plotly_dark")

  basic_plot.update_layout({
    "title": "Ratings evolution",
    "xaxis_title": "Months",
    "yaxis_title": "Average rating",
    "legend_title": "Brands"
  })

  i = 0
  for restaurant in ratings:
    basic_plot["data"][i]["name"] = "Restaurant {}".format(i+1)

    basic_plot["data"][i]["hovertemplate"] = "{}={}<br>{}=%{{x}}<br>{}=%{{y}}<extra></extra>".format(
      "Month",
      basic_plot["data"][i]["name"],
      "Brand",
      "Average rating"
    )
    i +=1

  graph = basic_plot.to_html(full_html=False)
  return render_template("index.html", graph=graph)

Which renders this: enter image description here

As I'm going to have many more restaurants, I'd like to add a dropdown filter to be able to select 1 or more restaurant (and by default have only 1 selected) and have the graph automatically updated based on the selection. Same for the months as I'm going to get larger time frames.

I found some examples for Plotly but nothing for Plotly Express. Please note that I'm not using Pandas but lists/dicts of Flask models loaded from a PSQL database.

Thanks for the help


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...