【问题标题】:How to set ticklabel rotation and add bar annotations如何设置刻度标签旋转并添加条形注释
【发布时间】:2021-12-21 20:53:13
【问题描述】:

我想绘制以下带有注释的条形图,并且我想将 x-label 保持 45 度,以便于阅读。我不确定为什么我的代码不起作用。我已将示例数据和所需的条形图添加为附件。我很感激你的建议!谢谢!

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

#sns.set(rc={"figure.dpi":300, 'savefig.dpi':300})
sns.set_context('notebook')
sns.set_style("ticks")
#sns.set_style('white')
sns.set_context("paper", font_scale = 2)
colors = ['b', 'g', 'r', 'c', 'm']
#sns.set(style="whitegrid")
#sns.set_palette(sns.color_palette(colors))

#fig, (ax1,ax2) = plt.subplots(1, 2, figsize=(16, 8))
#fig.subplots_adjust(wspace=0.3)

plots1 = sns.barplot(x="Model", y="G-mean", data=df_Aussel2014_5features, ax=ax1,palette='Spectral')
# Iterrating over the bars one-by-one
for bar in plots1.patches:

    # Using Matplotlib's annotate function and
    # passing the coordinates where the annotation shall be done
    plots1.annotate(format(bar.get_height(), '.2f'),
                (bar.get_x() + bar.get_width() / 2,
                    bar.get_height()), ha='center', va='center',
                size=10, xytext=(0, 5),
                textcoords='offset points')
plt.show()
# Save figure
#plt.savefig('Aussel2014_5features.png', dpi=300, transparent=False, bbox_inches='tight')

我得到了以下图片。

【问题讨论】:

    标签: python pandas matplotlib seaborn bar-chart


    【解决方案1】:
    • 您正在使用面向对象的接口(例如axes),所以不要混合使用plt.axes. 方法
    • seaborn.barplot 是一个坐标轴级别的绘图,它返回一个 matplotlib 坐标轴,在本例中为 p1
    • 使用matplotlib.axes.Axes.tick_params 设置轴的旋转,或一些其他参数,如文档中所示。
    • 使用matplotlib.pyplot.bar_label 添加条形注释。
      • 请参阅此answer,了解更多详细信息和使用该方法的示例。
    • 根据需要调整nrowncolsfigsize,并设置sharex=Falsesharey=False
    • python 3.8.12pandas 1.3.4matplotlib 3.4.3seaborn 0.11.2中测试
    import seaborn as sns
    import matplotlib.pyplot as plot
    import pandas as pd
    
    # data
    data = {'Model': ['QDA', 'LDA', 'DT', 'Bagging', 'NB'],
            'G-mean': [0.703780, 0.527855, 0.330928, 0.294414, 0.278713]}
    
    df = pd.DataFrame(data)
    
    # create figure and axes
    fig, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(8, 8), sharex=False, sharey=False)
    
    # plot
    p1 = sns.barplot(x="Model", y="G-mean", data=df, palette='Spectral', ax=ax1)
    p1.set(title='Performance Comparison based on G-mean')
    
    # add annotation
    p1.bar_label(p1.containers[0], fmt='%0.2f')
    
    # add a space on y for the annotations
    p1.margins(y=0.1)
    
    # rotate the axis ticklabels
    p1.tick_params(axis='x', rotation=45)
    

    【讨论】:

      【解决方案2】:

      matplotlib.pyplot 导入为pltplt.xticks(rotation=‌​45)

      例子:

      import matplotlib.pyplot as plt
      
      plt.xticks(rotation=‌​45)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-11
        • 1970-01-01
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-05
        相关资源
        最近更新 更多