Label axes on Seaborn Barplot

前端 未结 3 1186
眼角桃花
眼角桃花 2020-12-22 18:45

I\'m trying to use my own labels for a Seaborn barplot with the following code:

import pandas as pd
import seaborn as sns

fake = pd.DataFrame({\'cat\': [\'r         


        
相关标签:
3条回答
  • 2020-12-22 19:20

    One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

    matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

    Solution code:

    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)
    

    Output figure:

    0 讨论(0)
  • 2020-12-22 19:27

    You can also set the title of your chart by adding the title parameter as follows

    ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')
    
    0 讨论(0)
  • 2020-12-22 19:28

    Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:

    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()
    
    0 讨论(0)
提交回复
热议问题