0

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.

1
  • You will need to create a minimal reproducible example, such that people can run your code. Also you would need to make it clear if the output your are concerned about is the one from matplotlib or from mpld3. Commented Aug 6, 2019 at 20:38

1 Answer 1

2

You have a couple options. You can do this when setting xticklabels or using 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) 

Of course, you have to specify what your tick labels should be.

On a side note, I do not make my figures the same way you do (as you see in the example), which may or may not influence how you change your figure.

Sign up to request clarification or add additional context in comments.

3 Comments

I'll try using your answer and see how things work. Thank you!
I haven't been able to successfully incorporate this method of making figures into my code. I just don't really understand it. Do you recommend any particular readings that can help guide me from the stage of making a figure, to the stage of transferring the figure to html, to be able to display the bar chart on a webpage? Thank you.
@JohnAbdelmalek I guess I don't see the issue. Perhaps if you answer ImportanceOfBeingErnest's questions and provide the MWE you can get more help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.