0

I have long labels and want to make a bar chart. I have used almost every solution given on stack overflow but none seemed to work. The labels come on top of each other and are not visible. This is the chart being made right now:-

enter image description here

and the code that I am using to produce this plot is:-

with open('features', 'rb') as fp:
    X=pickle.load(fp)

with open('labels', 'rb') as fp:
    y=pickle.load(fp)

from sklearn.feature_selection import mutual_info_classif

imp=mutual_info_classif(X,y)
#getting mutual information

imp=np.array(imp)*100


df_item=pd.read_excel('item_label.xlsx')

items=list(df_item['Item_id'].astype(str).values)


ids=["220045","220046","220047","220050","220051","220059","220060","220210","220603","224167",
    "224643","225108","225122","225664","227007","227242","227243","227688","227916","227918","227919"
    ,"227923","227925","227926"]

df_item=df_item[df_item['Item_id'].isin(ids)]
vals=list(df_item['Label'].values)
#plotting mutual info with features names

people=["GENDER","ADMISSION_TYPE","ADMISSION_LOCATION","RELIGION","MARITAL_STATUS","ETHNICITY",
    "DIAGNOSIS"]

arr=[]
for p in people:
    arr.append(p)
for v in vals:
    arr.append(v)
people=arr

import matplotlib.pyplot as plt

heights = imp
bars = people

f, ax = plt.subplots(figsize=(18,5))
plt.bar(bars, heights)
plt.savefig('mutual_info.png')

and this is something that I want:-

enter image description here

Any help will be much appreciated. I have been struggling a lot in doing this.

Asim
  • 1,430
  • 1
  • 22
  • 43

1 Answers1

1

Use rotation with xticks() or axes.set_xticklabels().

plt.xticks(x, labels, rotation='vertical')  # you can set rotation to an angle as well (eg: 90)

Refer to this example:

https://matplotlib.org/gallery/ticks_and_spines/ticklabels_rotation.html

So, this code should be modified as:

f, ax = plt.subplots(figsize=(18,5))
ax.bar(bars, heights)
ax.set_xticklabels(bars, rotation=90)
Supratim Haldar
  • 2,376
  • 3
  • 16
  • 26
  • I tried this:- "plt.xticks(heights, bars, rotation='vertical')" but this erases the ticks. I want to enlarge the space rather than rotating it. – Asim May 19 '19 at 19:02
  • Your x value should be bars, if I understood your code correctly. So try `plt.xticks(bars, bars, rotation='vertical')`. – Supratim Haldar May 19 '19 at 19:04