'How to position the bar graph while using DataFrame so that the y-aixs coordinates will be shown completely in the saved .png file

I am using a dictionary through DataFrame to plot a barh graph, as:

import pandas as pd
#data is a dictionary and index is a list
df = pd.DataFrame (data = data, index = index)
df.plot.barh(stacked= True, figsize= (15,8), fontsize = 14, postion = 2.5, title="Thinking about it")

fig = plt.gcf()
fig.savefig('tts_tds.png')

The problem that I am facing is when I open the .png file, as the contents in the index have larger strings in it, they are not completely shown in the y-axis, i.e, the coordinates of y-axis are half cut.

For example: if one of the elements in the index is 'ABCDEFGHIJKLMNOP QRSTUVWXYZ 1234TSR' then in the .png file, at y-axis the coordinate is shown as: ABCDEFGHI

I know about the argument named as postion that can be passed in df.plot.barh() to position the bar graph. But when I increase the number above 1 (like 2 or 3 or 5) the coordinates shift upwards and not towards right side.

So, if there is any way through which I can resolve this problem regarding positioning the graph please let me know or if there is a way by which I will be able to represent the coordinates separately in a vertical or horizontal column aside or below the graph then please tell me how to do it.

Below as in way below x-axis and not getting into the x-axis coordinates or just like a separate image but still as a part of the graph.



Solution 1:[1]

If you save the fig with bbox_inches="tight" (matplotlib documentation savefig), it will accommodate the long string. I'm not sure about the "position" argument, I received an error with that included. I think this is what you meant: Chart

import pandas as pd
import matplotlib.pyplot as plt

# DataFrame
data = {'factor1': [5,4,3], 'factor2': [9, 4, 3]}
index = ["ABCDEFGHIJKLMNOP QRSTUVWXYZ 1234TSR", "two", "three"]
df = pd.DataFrame (data = data, index = index)

# Plot
fig, ax = plt.subplots()
df.plot.barh(stacked= True, figsize= (15,8), fontsize = 14, title="Thinking about it", ax=ax)
fig.savefig('tts_tds.png', bbox_inches="tight")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rawson