首页 > 编程问答 >多个箱线图,其中包含 for 循环保存输出中文件的数据?

多个箱线图,其中包含 for 循环保存输出中文件的数据?

时间:2024-07-26 10:31:55浏览次数:5  
标签:python boxplot nested-for-loop

我正在使用保存在要绘制箱线图的文件中的一些数据。

每个文件(第 3 行)中有 27 个值,每个文件我希望成为沿 x 轴 5 ' 的单独箱线图

然后,我还希望将每个文件作为单个箱线图进行概述,因为我有 10 个“对象”(使用所有 5 个文件 27 个值(135 个值)作为单个箱线图)

我已经开始在代码上,但目前我只给出了一个箱线图,因为我认为它没有正确保存数据以便能够绘制多个箱线图,到目前为止我还没有开始组合整个图形的数​​据。|| |任何帮助将不胜感激。

` import numpy as np 从 numpy 导入 genfromtxt 将 matplotlib.pyplot 导入为 plt import pandas as pd

`

dataset = pd.read_excel("ObjectData.xlsx") #Where the names of the Objects are kept
data = []

#Iterations for objects and runs
for object in range(0, 10, 1):
    for run in range(0, 5, 1):

        #Access data from files
        recordname1 = str(dataset.iloc[object, 1]) + " run:" + str(run) #Object and run name
        path1 = recordname1 + "clonemin.csv"
        my_plot_data = genfromtxt(path1, delimiter=',') #Get individual file (eg 1of10,1of5)
        data = [data, np.append(my_plot_data,([3, :]))] #Get individual line from file R=3, C=all

        #Save individual boxplots for plotting
        fig = plt.figure(figsize=(10,7))
        ax = fig.add_axes([0,0,1,1])
        bp = ax.boxplot(data)
        plt.show()

    #Save object boxplots (1x5) iteratedx10
    path2 = str(dataset.iloc[object, 1]) + "Boxplot.png" 
    plt.savefig(path2)
    plt.clf()

path3 = "Final_Boxplot.png" #Save overall boxplots (1x10)
plt.savefig(path3)
plt.clf()

结果应该是:对于每个对象 (10),应该有一个由 5 个箱线图组成的图形,以及一个沿 x 轴显示 10 个对象箱线图的整体图形。总共 11 张图片。

Result should be: For each object (10) there should be a graphic made up of 5 boxplots, and one overall graphic showing the 10 objects boxplots along the x-axis. So 11 Images overall.


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

dataset = pd.read_excel("ObjectData.xlsx")
# Create a figure to store all object boxplots
fig_all_objects = plt.figure(figsize=(10, 7))

for object in range(0, 10, 1):
    data_object = []  # Store data for all runs of current object
    for run in range(0, 5, 1):
        recordname1 = str(dataset.iloc[object, 1]) + " run:" + str(run)
        path1 = recordname1 + "clonemin.csv"
        my_plot_data = genfromtxt(path1, delimiter=',')
        data_object.append(my_plot_data) 

    # Create a figure for each object
    fig_object = plt.figure(figsize=(10, 7))
    ax_object = fig_object.add_axes([0, 0, 1, 1])
    # Boxplot for all runs of current object
    bp = ax_object.boxplot(data_object)
    ax_object.set_xticklabels([f"Run {i+1}" for i in range(5)])
    ax_object.set_title(f"Object {dataset.iloc[object, 1]}")
    plt.savefig(f"{dataset.iloc[object, 1]}_Boxplot.png") 
    plt.close(fig_object) 

    # Add data to the overall figure
    ax_all_objects = fig_all_objects.add_axes([0, 0, 1, 1])
    bp_all = ax_all_objects.boxplot(data_object, positions=[object * 5 + i for i in range(5)])

# Customize and save the overall boxplot
ax_all_objects.set_xticks([i * 5 + 2 for i in range(10)])
ax_all_objects.set_xticklabels([dataset.iloc[i, 1] for i in range(10)])
plt.savefig("Final_Boxplot.png")
plt.close(fig_all_objects)

Here's how this code works:

  1. Data Loading & Initialization:
  2. Reads object names from "ObjectData.xlsx."
  3. Initializes lists to store data for plotting.

  4. Iterating Through Objects and Runs:

  5. Loops through each object and its corresponding runs.
  6. Constructs file names for each run's data.
  7. Reads data from each file using genfromtxt .

  8. Creating and Saving Individual Object Boxplots:

  9. For each object, creates a new figure ( plt.figure ).
  10. Appends the data for all 5 runs of the object to data_object .
  11. Generates a boxplot ( ax.boxplot ) using the collected data.
  12. Sets labels for the x-axis ticks (Run 1 to Run 5).
  13. Sets the title of the plot with the object's name.
  14. Saves the figure as a PNG file named "{Object Name}_Boxplot.png".
  15. Clears the figure to prepare for the next object's plot.

  16. Creating and Saving the Overall Boxplot:

  17. Creates a new figure ( plt.figure ) for the overall boxplot.
  18. Iterates through the data of each object and its runs.
  19. For each object, adds its data to the overall boxplot ( ax.boxplot ) at specific positions along the x-axis to avoid overlap.
  20. Sets custom x-axis ticks and labels to represent each object.
  21. Saves the final overall boxplot as "Final_Boxplot.png".

  22. Output:

  23. The code generates 11 images in total:
    • 10 images named "{Object Name}_Boxplot.png" each showing boxplots for the 5 runs of a specific object.
    • 1 image named "Final_Boxplot.png" showing an overall boxplot combining the data of all 10 objects.

标签:python,boxplot,nested-for-loop
From: 78796032

相关文章

  • python-myStudyList
     1  下载软件1.1下载python最新版本并安装下载地址:百度搜索python官网。WelcometoPython.org。 1.2官网学习网页:PythonTutorials–RealPython   1.3也可以下载集成环境软件Anaconda。 Anaconda软件商城官方正版免费下载(msc23.cn) 2 ......
  • Python语法基础
    基本语句输入input() eg:输出print(内容)注释单行注释:#注释内容多行注释:"""注释内容"""数据类型: 字面量:整型、浮点数、字符串......intfloatstring查看数据类型:type(数据)查看数据类型 转换函数int(x):将x转换成整数类型float(x):将x转......
  • PyTesseract 不提取文本?我是所有这些Python的新手,请需要h3lp
    它不想从图像中提取文本,就像终端保持黑色并带有空格,就像它实际上试图提取文本一样,这是我的代码和图像从PIL导入图像导入pytesseract导入CV2“C:\用户\埃米利亚诺\下载\practic.png”pytesseract.pytesseract.tesseract_cmd="C:\ProgramFiles\Tesseract-OCR\tesseract.exe......
  • Python安装第三方库
    Python安装PILPIL(PythonImagingLibrary)是一个旧的Python库,用于处理图像。然而,PIL已经不再维护,并被一个名为Pillow的库所取代。Pillow是PIL的一个分支,并且完全兼容PIL。建议使用Pillow而不是PIL。pipinstallpillowPython安装moviepymoviepy是一个用于视频编辑的Python库,......
  • 优化Python中图像中的OCR文本检测
    我目前正在用python编写一个程序,该程序获取包含大量文本的图像,将其提取到.txt文件,然后将找到的单词与另一个文件中的单词列表进行比较,并创建一些坐标(根据像素)在图像中找到的单词中,如果找到图像,则会在图像中绘制红色方块。到目前为止,我已经正确处理了坐标部分,在单词周围绘制了......
  • Python保存字典类型数据到文件的三种方法
    1、在Python中使用pickle模块的dump函数将字典保存到文件中importpicklemy_dict={'Apple':4,'Banana':2,'Orange':6,'Grapes':11}#保存文件withopen("myDictionary.pkl","wb")astf:pickle.dump(my_dict,tf)......
  • 《最新出炉》系列入门篇-Python+Playwright自动化测试-53- 处理面包屑(详细教程)
    1.简介面包屑(Breadcrumb),又称面包屑导航(BreadcrumbNavigation)这个概念来自童话故事“汉赛尔和格莱特”,当汉赛尔和格莱特穿过森林时,不小心迷路了,但是他们发现沿途走过的地方都撒下了面包屑,让这些面包屑来帮助他们找到回家的路。所以,面包屑导航的作用是告诉访问者他们在网站中......
  • 如何使用 Python 在 Telegram 中进行标签搜索
    Telegram最近添加了一项新功能,可以在所有公共频道中同时按主题标签进行搜索:https://telegram.org/blog/message-effects-and-more#hashtag-search如何进行此类搜索用蟒蛇?(Telethon,Python-Telegram-Bot,...)我在Telethon文档中找到了这个函数:https://tl.......
  • 使用 Python 构建一个简单的 REST API
    使用Python构建一个简单的RESTAPI简介本文档将引导您使用Python和Flask框架构建一个简单的RESTAPI。我们将创建一个API,用于管理一个虚拟的书籍数据库。准备工作Python环境:确保您的系统上安装了Python3.x。Flask框架:使用pip安装Flask:pipinstallFla......
  • python学习之闭包与装饰器
    一、闭包闭包允许一个函数访问并操作函数外部的变量(即父级作用域中的变量),即使在该函数外部执行。特性:(1)外部函数嵌套内部函数。(2)外部函数可以返回内部函数。(3)内部函数可以访问外部函数的局部变量。defout():print("我是外层")n=10defins():......