0

I can't seem to get the labels on the x-axis to rotate 90 degrees.

Example df:

import pandas as pd import matplotlib.pyplot as plt d = ({ 'A' : ['1','1','2','2','3','3','3'], 'B' : ['A','B','C','C','D','B','C'], 'C' : ['Foo','Bar','Foo','Bar','Cat','Bar','Cat'], }) df = pd.DataFrame(data=d) fig,ax = plt.subplots(figsize = (9,4)) df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar') plt.show() 

I have tried the basic:

plt.xticks(rotation = 90) 

Also tried this but it returns an Attribute Error:

df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar', rotation = 90) 

I have got the labels to rotate through this:

xticklabels = df.C.unique() ax.set_xticklabels(xticklabels, rotation = 0) 

But it returns incorrect ordering. It just takes the values as they appear. Rather than determining the appropriate label

1

2 Answers 2

2

I run the code below to produce the labels with angle 0. I don't understand why there are two plots generated so I deleted the line fig,ax = plt.subplots()

import pandas as pd import matplotlib.pyplot as plt d = ({ 'A' : ['1','1','2','2','3','3','3'], 'B' : ['A','B','C','C','D','B','C'], 'C' : ['Foo','Bar','Foo','Bar','Cat','Bar','Cat'], }) df = pd.DataFrame(data=d) #fig,ax = plt.subplots() df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar') plt.xticks(rotation = 0) plt.show() 

enter image description here

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

Comments

1

You can control the xticks labels through creating a subplot and configuring the label settings, like this:

import pandas as pd import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1) d = ({ 'A' : ['1','1','2','2','3','3','3'], 'B' : ['A','B','C','C','D','B','C'], 'C' : ['Foo','Bar','Foo','Bar','Cat','Bar','Cat'], }) df = pd.DataFrame(data=d) udf = (df.assign(A=df.A.astype(int)) .pivot_table(index="C", columns="B", values="A",aggfunc='count') .rename_axis(None) .rename_axis(None,1)) udf.plot(kind='bar', ax=ax) labels = ax.set_xticklabels(udf.index.values, rotation=0, fontsize=14) 

The output would be: O rotation and bigger fontsize

One more thing, I think you need 0 degree rotation as the default is 90.

PS: Long chaining in pandas operations really eats away the readability.

Comments