修改pandas boxplot输出

时间:2016-10-19 08:04:20

标签: python pandas matplotlib

根据文件记载,我在大熊猫中制作了这个情节:

import pandas as pd
import numpy as np
import pyplot as plt

df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])
df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20))
plt.figure()
bp = df.boxplot(by="models")

enter image description here

如何修改此图?

我想:

  • 修改从(2,2)到(1,4)
  • 的安排
  • 更改标签和标题,文字和字体大小
  • 删除'[models]'文字

如何将此图保存为pdf?

2 个答案:

答案 0 :(得分:3)

  • 使用layout
  • 进行安排
  • 设置x标签时使用set_xlabel('')
  • 图标题使用figure.subtitle()
  • 要更改数字大小,请使用figsize=(w,h)(英寸)

注意:行np.asarray(bp).reshape(-1)正在将子图的布局(例如2x2)转换为数组。

代码:

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

df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])
df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20))
bp = df.boxplot(by="models",layout=(4,1),figsize=(6,8))
[ax_tmp.set_xlabel('') for ax_tmp in np.asarray(bp).reshape(-1)]
fig = np.asarray(bp).reshape(-1)[0].get_figure()
fig.suptitle('New title here')
plt.show()

结果:

enter image description here

答案 1 :(得分:2)

您可以使用pandas中的boxplot函数执行许多操作,请参阅documentation

  • 您可以修改排列,并更改fontsize:

    import pandas as pd
    import numpy as np
    import pyplot as plt
    
    df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])
    df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20))
    bp = df.boxplot(by="models", layout = (4,1), fontsize = 14)
    
  • 更改列标签可以通过更改数据框本身的列标签来完成:

    df.columns(['E', 'F', 'G', 'H', 'models'])
    
  • 为了进一步定制,我将使用matlotlib本身的功能;您可以查看示例here