【发布时间】:2019-12-14 10:55:46
【问题描述】:
我无法旋转 matplotlib 条形图上的 x 刻度标签,因此这些标签当前重叠。我已经阅读了一些 matplotlib 文档以及其他阅读,并尝试了不同的方法,但都没有奏效。根据我对所读内容的理解,似乎有不止一种方法可以使用 matplotlib 实现条形图,而且我不能在所有条形图上旋转刻度标签,只能在以某种方式制作的条形图上旋转。那准确吗?有没有办法在我的条形图上进行 x 轴刻度标签旋转?
(快速概述我正在尝试做的事情:我正在制作一个包含条形图的 Web 应用程序。我正在处理的条形图应该在 x- 上显示癌症药物副作用的名称轴,以及 y 轴上每种副作用的发生百分比。副作用标签很长,因此它们重叠,这就是我尝试旋转它们的原因。)
这里是python代码:
import os
import matplotlib.pyplot as plt
import numpy as np
import mpld3
from matplotlib import *
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":
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)
positions =
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
fig, ax = plt.subplots()
fig = plt.figure(figsize=(7,6))
ax = plt.bar(keys, values, width=0.5)
plt.xlabel("Side Effects")
plt.xticks(positions, keys)
plt.xticks(rotation=60)
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")
fig = ax[0].figure
bar_chart = mpld3.fig_to_html(fig)
return render_template("breastcancer.html", bar_chart = bar_chart)
else:
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
plt.xticks(rotation=60) 线用于将 x 轴刻度标签旋转 60 度(我只是选择了 60 度,这个确切数字没有具体原因)。然而,标签根本不旋转,但奇怪的是名为“副作用”的 x 轴标签消失了。当我删除 plt.xticks(rotation=60) 行时,“副作用”标签会重新出现在它的位置。
感谢您的帮助。
【问题讨论】:
-
您需要创建一个minimal reproducible example,以便人们可以运行您的代码。此外,您还需要说明您关心的输出是来自 matplotlib 还是来自 mpld3。
标签: python matplotlib rotation mpld3