0

As the title suggests, my categorical data in the y axis of a horizontal bar plot have quite a few words. A string, such as "This is an example of my categorical data size" gets cut no matter how much I change the figsize. Is there a way to widen that part of the plot, or maybe put the data as multiple lines so the line fit and be fully readable?

In case it's helpful, I use Greek characters, I'm not sure if it changes anything.

My code (it's for a dictionariy, used with a string as key and a float/int as the value):

from matplotlib.ticker import EngFormatter
import numpy as np
import matplotlib.pyplot as plt


example_dict = {"A random very long string to showcase the example": 50000000,
                "Another random smaller string": 3500000000,
                "A small string": 700000000,
                "String": 100000000,
                "Another larger than usual example string that will get sadly cut": 70000000}


def categorical_horizontal_bar_numbers1(dataset, fig_dim=(10, 5), title="", x_label="",
                                        y_label=""):
    fmt = EngFormatter(places=0)

    fig, ax = plt.subplots(figsize=fig_dim)
    width = 0.75  # the width of the bars
    ind = np.arange(len(dataset.values()))  # the x locations for the groups
    ax.barh(ind, dataset.values(), width, color="blue")
    ax.set_yticks(ind + width / 2)
    ax.set_yticklabels(dataset.keys(), minor=False)

    plt.grid(False)
    plt.title(title)
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    ax.xaxis.set_major_formatter(fmt)

    for i, v in enumerate(dataset.values()):
        ax.text(v + 500, i, s=fmt.format_eng(v), color='blue', va='center')

    plt.show()

categorical_horizontal_bar_numbers1(example_dict,fig_dim=(30,10))
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Serelia
  • 213
  • 2
  • 6
  • 1
    Your [mre] should include an example of the data - `dataset`. – wwii Feb 09 '21 at 22:09
  • 1
    Does `plt.tight_layout()` just before `plt.show()` help in your case? Also, you could manually (or via some code) add newline characters in the strings to get something like `"A random very long\nstring to showcase\nthe example"` which would then be written on multiple lines. Also see [Wrapping long y labels](https://stackoverflow.com/questions/15740682/wrapping-long-y-labels-in-matplotlib-tight-layout-using-setp/15740730) – JohanC Feb 10 '21 at 00:17
  • @JohanC Using tight_layout() actually worked! It doesn't look as fancy, but it does the job, so it's good enough (and without needing to end up doing it manually). The linked question is also really useful, thank you! If you'd like, you can post it as an answer so I can mark it as the correct one, or I could answer it myself and tag you, whichever you prefer. – Serelia Feb 10 '21 at 00:43

0 Answers0