修改Pandas方块图输出

2024-06-10 17:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

根据文献记载,我在熊猫身上画了这个情节:

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)
  • 更改标签和标题、文本和字体大小
  • 删除“[模型]”文本

如何将此绘图保存为pdf格式?


Tags: 文本importnumpy绘图dataframepandasdfmodels
2条回答
  • 对于这种安排,使用layout
  • 使用set_xlabel('')设置x标签
  • 对于图形标题,请使用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

在pandas中已经可以使用boxplot函数执行许多操作,请参见documentation

  • 您已经可以修改排列,并更改字体大小:

    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

相关问题 更多 >