Search code examples
pythonnumpymatplotlibpandasgraphing

Pandas and Matplotlib - how can I change plot area to fit in more x-axis text?


Say I read in this csv file into a pandas dataframe:

File contents:

Strings, Values, Letters
Made up data, 55.0, A
with long text strings for index, 125.5, B
with long text strings for index, 85.5, B
how does one, 1.3, A
how does one, 12.3, A
change the plot area to, 96.1, B
fit all of this text in?, 0.2, B
fit all of this text in?, 47.2, B

Code:

c=pd.read_csv('myfile.csv')

Gives:

                            Strings   Values  Letters
0                      Made up data     55.0        A
1  with long text strings for index    125.5        B
2  with long text strings for index     85.5        B
3                      how does one      1.3        A
4                      how does one     12.3        A
5           change the plot area to     96.1        B
6          fit all of this text in?      0.2        B
7          fit all of this text in?     47.2        B

I then use groupby to sum the strings:

g=c.groupby(u'Strings').sum()

Giving:

                                   Values
Strings                                  
Made up data                         55.0
change the plot area to              96.1
fit all of this text in?             47.4
how does one                         13.6
with long text strings for index    211.0

And finally plot like so:

g.plot(kind='bar')

Giving:

enter image description here

As you can see the x axis text is badly cropped. How can I fix this?

Note that I have tried using the rot parameter (e.g. rot=-45) but this is insufficient.

I imagine that a solution might involve setting the plot area but I'm unsure how to do this.


Solution

  • Have you tried: plt.tight_layout()