简体   繁体   English

如何将 y 轴标签添加到 df.boxplot

[英]How to add y-axis label to df.boxplot

I generate a boxplot out of a dataframe with:我从数据框中生成一个箱线图:

bplot = df.boxplot(
    column=column_name,
    by=list1,
    fontsize=8,
    layout=(2,1),
    rot=90,
    figsize=(25,20)
)

Where df is my dataframe, column_name is my wanted column and list1 is the list to use for groupby?其中df是我的数据框, column_name是我想要的列,而list1是用于 groupby 的列表?

I want to label my y-axis with a string.我想用字符串标记我的 y 轴。 Tried this:试过这个:

plt.ylabel('ylabel')

but does not work.但不起作用。

DataFrame.boxplot() function returns Axes object. DataFrame.boxplot() 函数返回 Axes 对象。 So, instead of using bplot.ylabel('ylabel') which is the function for pyplot object, try to use:因此,不要使用bplot.ylabel('ylabel')这是 pyplot 对象的函数,而是尝试使用:

bplot.set_ylabel('ylabel')

If you still got errors, make sure to write the line right after you call the boxplot() function.如果仍然出现错误,请确保在调用 boxplot() 函数后立即编写该行。

As an alternative, you could also create pyplot subplots first which generates the axes object that you need.作为替代方案,您还可以先创建 pyplot 子图,以生成您需要的轴对象。 And then you can specify the axes object on the boxplot function arguments:然后您可以在 boxplot 函数参数上指定轴对象:

from matplotlib import pyplot as plt
fig, ax = plt.subplot()
ax = df.boxplot(
    column=column_name,
    by=list1,
    fontsize=8,
    layout=(2,1),
    rot=90,
    figsize=(25,20),
    ax=ax
)

You need first to define the pd.DataFrame.boxplot() return_type parameter as 'axes' .您首先需要将pd.DataFrame.boxplot() return_type参数定义为'axes' It will return a pandas.Series with single value containing the matplotlib.axes._subplots.AxesSubplot object.它将返回一个包含matplotlib.axes._subplots.AxesSubplot对象的具有单个值的pandas.Series You can then manipulate this object like any matplotlib axes object:然后,您可以像操作任何 matplotlib 轴对象一样操作此对象:

bbplot = df.boxplot(column=column_name,
                    by=list1,
                    fontsize=8,
                    layout=(2,1),
                    rot=90,
                    figsize=(25,20),
                    return_type='axes')

bbplot[0].set_ylabel('yaxis')

尝试这个:

bplot.set_ylabel('ylabel')

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

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