I cannot rotate the x tick labels on a matplotlib bar chart, so those labels currently overlap. I've done some matplotlib documentation reading as well as other reading, and tried different approaches, yet none have worked. From my understanding of things I've read, it seems that there's more than one way to implement a bar chart using matplotlib, and that I cannot rotate tick labels on all bar charts, only on bar charts made in certain way(s). Is that accurate? Is there a way to do the x-axis tick labels rotation on my bar chart?
(Quick overview of what I'm trying to do: I'm making a web application, that includes a bar chart. The bar chart I'm working on should display names of side effects of cancer medications on the x-axis, and percentages of occurrence of each of those side effects on the y-axis. The side effects labels are long, so they overlap, and that's why I'm trying to rotate them.)
Here is the python code:
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) The plt.xticks(rotation=60) line is meant to rotate the x-axis tick labels by 60 degrees (I just chose 60 degrees, no specific reason for that exact number). However, the labels do not rotate at all, but strangely the x-axis label called "Side Effects" disappears. When I remove the plt.xticks(rotation=60) line, the "Side Effects" label re-appears in its place.
Thank you for your help.