首页 > 解决方案 > 使轴上的长标签可见

问题描述

我有很长的标签,想制作一个条形图。我已经使用了几乎所有关于堆栈溢出的解决方案,但似乎没有一个有效。标签相互重叠,不可见。这是现在正在制作的图表:-

在此处输入图像描述

我用来制作这个情节的代码是:-

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')

这是我想要的东西:-

在此处输入图像描述

任何帮助都感激不尽。我一直在努力做到这一点。

标签: python-3.xmatplotlibaxis-labels

解决方案


rotationxticks()或一起使用axes.set_xticklabels()

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

参考这个例子:

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

所以,这段代码应该修改为:

f, ax = plt.subplots(figsize=(18,5))
ax.bar(bars, heights)
ax.set_xticklabels(bars, rotation=90)

推荐阅读