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

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

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

import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

folder_path = "path to image folder"

# Get a list of the TIFF image in the folder
tiff_files = [f for f in os.listdir(folder_path) if f.endswith('.tiff')]

# Loop through the images in the folder
grey_values = []
for img_file in tiff_files:
    img = Image.open(os.path.join(folder_path, img_file))
    grey_values.append(np.asarray(img).ravel())

# Plot the grey values as a box graph
plt.boxplot(grey_values)
plt.title('Grey Values of TIFF Images')
plt.xlabel('Image')
plt.ylabel('Grey Value')
plt.show()

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

ykejflvf

ykejflvf1#

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

plt.figure(figsize=(16, 8))
plt.boxplot(grey_values)

# Set xticks, requires values and labels
xticks_range = range(1, len(tiff_files) + 1)
plt.xticks(xticks_range ,labels=tiff_files, rotation=45, ha="right")

plt.title('Grey Values of TIFF Images')
plt.xlabel('Image')
plt.ylabel('Grey Value')
plt.show()

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

相关问题