matplotlib 如何在x轴箱线图中的每个文件名中添加名称

1aaf6o9v  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(150)

当我运行代码查看箱形图时,我注意到图的x轴中没有文件名,而是显示1,2,3,4,5,6 .....
这是我现在正在研究的代码

  1. import os
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from PIL import Image
  5. folder_path = "path to image folder"
  6. # Get a list of the TIFF image in the folder
  7. tiff_files = [f for f in os.listdir(folder_path) if f.endswith('.tiff')]
  8. # Loop through the images in the folder
  9. grey_values = []
  10. for img_file in tiff_files:
  11. img = Image.open(os.path.join(folder_path, img_file))
  12. grey_values.append(np.asarray(img).ravel())
  13. # Plot the grey values as a box graph
  14. plt.boxplot(grey_values)
  15. plt.title('Grey Values of TIFF Images')
  16. plt.xlabel('Image')
  17. plt.ylabel('Grey Value')
  18. plt.show()

我试过添加“Label=tiff_files”,但它会抛出错误,并且不知如何将文件名替换为正常编号。

ykejflvf

ykejflvf1#

使用plt.xticks函数
下面是一个示例(在我的案例中使用.png文件)

  1. plt.figure(figsize=(16, 8))
  2. plt.boxplot(grey_values)
  3. # Set xticks, requires values and labels
  4. xticks_range = range(1, len(tiff_files) + 1)
  5. plt.xticks(xticks_range ,labels=tiff_files, rotation=45, ha="right")
  6. plt.title('Grey Values of TIFF Images')
  7. plt.xlabel('Image')
  8. plt.ylabel('Grey Value')
  9. plt.show()

请注意,如果您决定使用轴法设计图形,则可以直接使用ax.set_xticklabels函数

展开查看全部

相关问题