繁体   English   中英

如何旋转Matplotlib条形图上的X轴刻度标签? 尝试了几种方法,都没有用

[英]How to rotate x-axis tick labels on matplotlib bar chart? Tried several approaches, none worked

我无法旋转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)行时,“ Side Effects”标签将再次出现在其位置。

谢谢您的帮助。

您有两种选择。 您可以在设置xticklabels或使用tick_params时执行此操作。

fig = pl.figure(figsize=(5, 5))
ax0 = fig.add_subplot(111)

ax0.bar(x, height=2)

ax0.set_xticklabels(yourLabels, rotation=60)

# alternatively
ax0.tick_params(rotation=60)

当然,您必须指定刻度标签应该是什么。

附带说明一下,我的数字制作方式与您的示例不同(如示例所示),这可能会或可能不会影响您更改数字的方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM