【问题标题】:Label axes on Seaborn BarplotSeaborn Barplot 上的标签轴
【发布时间】:2015-10-16 10:20:57
【问题描述】:

我正在尝试将我自己的标签用于 Seaborn 条形图,代码如下:

import pandas as pd
import seaborn as sns

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', 
                  data = fake, 
                  color = 'black')
fig.set_axis_labels('Colors', 'Values')

但是,我收到一个错误:

AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'

什么给了?

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    Seaborn 的条形图返回一个轴对象(不是图形)。这意味着您可以执行以下操作:

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
    ax = sns.barplot(x = 'val', y = 'cat', 
                  data = fake, 
                  color = 'black')
    ax.set(xlabel='common xlabel', ylabel='common ylabel')
    plt.show()
    

    【讨论】:

    • seaborn 没有自己的方法来设置这些 - 不涉及 matplotlib ?
    • 所以一般规则是FacetGrid /任何方面都返回一个图形对象,而其他所有内容都返回一个轴对象?
    【解决方案2】:

    使用matplotlib.pyplot.xlabelmatplotlib.pyplot.ylabel可以避免set_axis_labels()方法带来的AttributeError

    matplotlib.pyplot.xlabel 设置 x 轴标签,而 matplotlib.pyplot.ylabel 设置当前轴的 y 轴标签。

    解决方案代码:

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
    fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
    plt.xlabel("Colors")
    plt.ylabel("Values")
    plt.title("Colors vs Values") # You can comment this line out if you don't need title
    plt.show(fig)
    

    输出图:

    【讨论】:

    • 我认为应该只是plt.show(fig)。它给了我 TypeError: show() 接受 1 个位置参数,但给出了 2 个。只是plt.show() 给了我想要的结果
    • 像这样分开做也有指定其他杂项matplotlib.text.Text属性的优点。我最常使用它来指定我们组织使用的自定义字体,方法是将 fontproperties 设置为 TTF 文件的位置。
    【解决方案3】:

    您还可以通过添加标题参数来设置图表的标题,如下所示

    ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')
    

    【讨论】:

    • 有没有办法改变ax.set()中标签和标题的字体大小?
    猜你喜欢
    • 2020-11-05
    • 2020-08-05
    • 2019-11-10
    • 2015-10-29
    • 2019-10-31
    • 2020-07-12
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    相关资源
    最近更新 更多