简体   繁体   English

使用 matplotlib python 防止分组条形图中的标签重叠

[英]Prevent overlapping labels in grouped bar chart using matplotlib python

I am using the following function to plot a grouped bar chart that compares between the performance of models built using imbalanced and balanced data.我正在使用以下 function 到 plot 分组条形图,比较使用不平衡和平衡数据构建的模型的性能。

# plot results to compare between balanced and imbalanced data

def barChartBalancing(imbalancedResults, rusResults, smoteResults, score, title, string):
    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np

    #make font bigger
    font = {'size'   : 15}

    matplotlib.rc('font', **font)
    
    labels = names
    
    x = np.arange(len(labels))  # the label locations
    width = 0.2  # the width of the bars

    fig, ax = plt.subplots(figsize=(10,9))
    rects1 = ax.bar(x - width, imbalancedResults, width, label='Imbalanced Dataset')
    rects2 = ax.bar(x , rusResults, width, label='RandomUnderSampler')
    rects3 = ax.bar(x + width, smoteResults, width, label='SMOTE')
    

    # Add some text for labels, title and custom x-axis tick labels, etc.
    ax.set_ylabel(score)
    ax.set_title(title)
    ax.set_xticks(x)
    ax.set_xticklabels(labels)
    ax.legend(loc='upper center')
    

    ax.bar_label(rects1, padding=5, fmt='%.2f', label_type='edge')
    ax.bar_label(rects2, padding=5, fmt='%.2f', label_type='edge')
    ax.bar_label(rects3, padding=5, fmt='%.2f', label_type='edge')

    fig.tight_layout()
    
    fileName = string +'.png'
    print(fileName)
    plt.savefig('figures/resampling/' + fileName)
    
    plt.show()

However, when I run this, the labels above the grouped bars are overlapping, like so:但是,当我运行它时,分组条上方的标签是重叠的,如下所示:

在此处输入图像描述

I tried changing the 'padding' value but then realised that is the distance between the and the end of the bar.我尝试更改“填充”值,但后来意识到这是条形图和条形图末端之间的距离。 I also tried changing the font size using fontsize argument in bar_label based on Rabinzel's comment, this kind of helped, but I have to make the font extremely small to prevent the overlapping completely, to the point where it is very hard to read.我还尝试根据 Rabinzel 的评论在 bar_label 中使用 fontsize 参数更改字体大小,这很有帮助,但我必须使字体非常小以防止完全重叠,以至于很难阅读。

Any ideas how I can fix the overlapping?有什么想法可以解决重叠问题吗? I wonder if I can position the labels vertically on the bar?我想知道我是否可以将 position 标签垂直放在酒吧? I think that would solve the issue without having to use extremely small font sizes.我认为这可以解决问题,而不必使用极小的字体。

I dont know if you have consider plotting your figure horizontally, but with this approach you will be able to:我不知道您是否考虑过水平绘制图形,但通过这种方法,您将能够:

  • have longer names as labels有更长的名称作为标签
  • you will not have the overlapping problem.你不会有重叠的问题。
  • an unlimited number of models (entries) in the same figure.同一图中的模型(条目)数量不限。
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

# Example data
models = ('Linear regresion', 'Singular vector machine', 'linear vector clasification',
          'Naive Bayes Classifier', 'Gradient boosting')
y_pos = np.arange(len(models))
distance = 3 + 10 * np.random.rand(len(models))
speed = 3 + 10 * np.random.rand(len(models))
age = 3 + 10 * np.random.rand(len(models))
width = 0.2 

rects1=ax.barh(y_pos-width, distance, width, align='center', label="Unvalance dataset")
rects2=ax.barh(y_pos, speed, width, align='center', label="Random under sapler")
rects3=ax.barh(y_pos + width, age, width, align='center', label="SMOTE")
ax.set_yticks(y_pos, labels=people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.bar_label(rects1, padding=5, fmt='%.2f', label_type='edge')
ax.bar_label(rects2, padding=5, fmt='%.2f', label_type='edge')
ax.bar_label(rects3, padding=5, fmt='%.2f', label_type='edge')
plt.legend()
plt.xlim(0,15)
plt.show()

在此处输入图像描述

Here is how you change fontsize and rotate the bar_label :以下是更改字体大小和旋转bar_label的方法:

example on one of them:其中之一的示例:

ax.bar_label(rects1, padding=5, fmt='%.2f', label_type='edge', fontsize=9, rotation='vertical')

You can also pass an integer to rotation if you like to have a different rotation: rotation=45如果您想进行不同的旋转,也可以将 integer 传递给旋转: rotation=45

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM