python - 我的条形图没有出现在屏幕上。我该如何解决?
问题描述
我正在尝试自学如何使用 matplotlib(在 Web 应用程序中)绘制条形图,其中 x 轴将具有各种癌症药物副作用,而 y 轴将具有每个这些副作用的发生百分比副作用。在 Web 应用程序的索引页面上,我有一个选择菜单,我要求用户从“下拉列表”中选择一种癌症。选择“乳腺癌”并单击“提交”(我已经为其创建了一个 html 文件)后,我希望上面讨论的条形图会出现在屏幕上。但是,我的屏幕上根本没有显示条形图。我究竟做错了什么?
这是python代码:
import os
import matplotlib.pyplot as plt
import numpy as np
np.random.seed()
from matplotlib.ticker import FuncFormatter
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template,
request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException,
InternalServerError
import sqlite3
app = Flask(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
db = SQL("sqlite:///cancermeds.db")
@app.route("/", methods=["GET", "POST"])
def index():
if request.method=="POST":
selection = request.form.get("cancerlist")
if selection == "breast cancer":
#db.execute used to extract info I will use to make
#list of keys (for x-axis) and list of values(for y-
#axis). Info extracted from table in SQLite3 database.
rows = db.execute("SELECT * FROM 'breast cancer'")
for row in rows:
keys = list(row.keys())
del keys[16:19]
print(keys)
values = list(row.values())
del values[16:19]
print(values)
fig = plt.figure(figsize=(7,6))
plt.bar(keys, values, width=0.5)
plt.xlabel("Side Effects")
plt.ylabel("Percentages of Occurence of Side
Effects")
plt.title("Bar Chart showing Side Effects of Breast
Cancer Medication(s) With Their Corrresponding Percentages Of
Occurence")
plt.legend()
plt.show()
return render_template("breastcancer.html")
else:
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
这是我终端中的所有内容:
~/environment/justforme/ $
~/environment/justforme/ $ FLAKS RUN
bash: FLAKS: command not found
~/environment/justforme/ $ flask run
* Serving Flask app "application.py" (lazy loading)
* Environment: development
* Debug mode: off
* Running on https://808d061b-7cdd-4348-ab06-3ede74c26f12-
ide.cs50.xyz:8080/ (Press CTRL+C to quit)
* Restarting with stat
INFO:werkzeug:192.168.133.245 - - [03/Aug/2019 19:13:30] "GET /
HTTP/1.0" 200 -
INFO:werkzeug:192.168.133.245 - - [03/Aug/2019 19:13:30] "GET
/static/styles.css HTTP/1.0" 404 -
DEBUG:cs50:SELECT * FROM 'breast cancer'
['diarrhea %', 'neutropenia %', 'nausea %', 'abdominal pain %',
'infections %', 'fatigue %', 'anemia %', 'leukopenia %', 'decreased
appetite %', 'vomiting %', 'headache %', 'alopecia %',
'thrombocytopenia %', 'peripheral neuropathy %', 'hepatotoxicity
%', 'cardiac side effects %']
[86, 41, 39, 29, 39, 40, 28, 21, 24, 28, 20, 16, 16, 0, 1, 0]
WARNING:matplotlib.legend:No handles with labels found to put in
legend.
['diarrhea %', 'neutropenia %', 'nausea %', 'abdominal pain %',
'infections %', 'fatigue %', 'anemia %', 'leukopenia %', 'decreased
appetite %', 'vomiting %', 'headache %', 'alopecia %',
'thrombocytopenia %', 'peripheral neuropathy %', 'hepatotoxicity
%', 'cardiac side effects %']
[27, 85, 30, 0, 24, 59, 33, 0, 36, 36, 14, 50, 68, 48, 36, 3]
WARNING:matplotlib.legend:No handles with labels found to put in
legend.
['diarrhea %', 'neutropenia %', 'nausea %', 'abdominal pain %',
'infections %', 'fatigue %', 'anemia %', 'leukopenia %', 'decreased
appetite %', 'vomiting %', 'headache %', 'alopecia %',
'thrombocytopenia %', 'peripheral neuropathy %', 'hepatotoxicity
%', 'cardiac side effects %']
[24, 8, 40, 19, 10, 50, 14, 1, 0, 19, 28, 0, 31, 32, 0.3, 1.8]
WARNING:matplotlib.legend:No handles with labels found to put in
legend.
INFO:werkzeug:192.168.133.245 - - [03/Aug/2019 19:13:34] "POST /
HTTP/1.0" 200 -
INFO:werkzeug:192.168.133.245 - - [03/Aug/2019 19:13:34] "GET
/static/styles.css HTTP/1.0" 404 -
作为初学者,请原谅我犯的任何可能非常基本的错误。谢谢!
解决方案
将绘图保存在文件中并<img src="/static/image.png">
在 HTML 中使用以显示它的最小示例。
from flask import Flask
import matplotlib.pyplot as plt
import os
app = Flask(__name__)
@app.route('/')
def index():
keys = [1,2,3,4]
values = [1,4,2,3]
plt.bar(keys, values, width=0.5)
plt.xlabel("Side Effects")
plt.ylabel("Percentages of Occurence of Side Effects")
plt.title("Bar Chart showing Side Effects of Breast \
Cancer Medication(s) With Their Corrresponding Percentages Of \
Occurence")
#plt.legend()
if not os.path.exists('static'):
os.makedirs('static')
plt.savefig('static/image.png')
return '''<DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body><img src="/static/image.png"></body>
</html>'''
if __name__ == '__main__':
app.run()
使用mpld3生成交互式绘图的最小示例。
一开始它只有工具:home(reset)、move、resize。
from flask import Flask
import matplotlib.pyplot as plt
import mpld3
app = Flask(__name__)
@app.route('/')
def index():
keys = [1,2,3,4]
values = [1,4,2,3]
ax = plt.bar(keys, values, width=0.5)
plt.xlabel("Side Effects")
plt.ylabel("Percentages of Occurence of Side Effects")
plt.title("Bar Chart showing Side Effects of Breast \
Cancer Medication(s) With Their Corrresponding Percentages Of \
Occurence")
#plt.legend()
fig = ax[0].figure
plt_html = mpld3.fig_to_html(fig)
return '''<DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>''' + plt_html + '''</body>
</html>'''
if __name__ == '__main__':
app.run()
使用seaborn 的最小示例,但它会创建静态图像。
from flask import Flask
import matplotlib.pyplot as plt
import seaborn as sns
import os
app = Flask(__name__)
@app.route('/')
def index():
keys = [1,2,3,4]
values = [1,4,2,3]
sns.barplot(keys, values)
plt.xlabel("Side Effects")
plt.ylabel("Percentages of Occurence of Side Effects")
plt.title("Bar Chart showing Side Effects of Breast \
Cancer Medication(s) With Their Corrresponding Percentages Of \
Occurence")
#plt.legend()
if not os.path.exists('static'):
os.makedirs('static')
plt.savefig('static/image.png')
return '''<DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body><img src="/static/image.png"></body>
</html>'''
if __name__ == '__main__':
app.run()
推荐阅读
- php - 将 onclick 事件的目标设置为特定位置
- sql - 如何从带有clob列的表中删除重复项?
- c - c - 正确的结构元素指针算法
- php - 我正在将一些数据传递给一个我想要存储到一个数组的文件,但是每次我传递数据时数组都从空开始,有什么建议吗?
- python - 编写代码以切换获胜者列表的顺序,使其现在按姓氏从 A 到 Z。将此列表分配给变量 z_winners
- google-sheets - 如何根据谷歌表格中的字符限制进行条件格式化
- python - nltk.downloader 给出 xml.etree.ElementsTree.ParseError
- javascript - 在 FileReader 中发生事件后 React JS 没有改变状态
- regex - 为什么正则表达式在 GSHEETS 和 GOOGLE DOCS 中表现不同
- google-cloud-platform - GCP 将所有外部端口转发到一个本地端口