Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Is it possible to move the colored points from the general legend to the text import os…

  1. User

    Is it possible to move the colored points from the general legend to the text

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

    Specify the folder paths

    input_folder = r"C:\Users\samuel.hernandez\OneDrive - FUNDECYT - PCTEX\Escritorio\Doctorado\Experimental\TGA" output_folder = r"C:\Users\samuel.hernandez\OneDrive - FUNDECYT - PCTEX\Escritorio\Doctorado\Experimental\TGA\Python\Test"

    Ensure the output folder exists

    os.makedirs(output_folder, exist_ok=True)

    def read_data_from_file(file_path): encodings = ['utf-8', 'iso-8859-1', 'cp1252'] for encoding in encodings: try: data = pd.read_csv(file_path, delim_whitespace=True, skiprows=1, encoding=encoding)

            temp_col = data.columns[1]  # Assuming temperature is the second column
            weight_col = data.columns[4]  # Assuming weight is the fifth column
            
            x_data = data[temp_col].str.replace(',', '.').astype(float)
            y_data = data[weight_col].str.replace(',', '.').astype(float)
            
            return x_data, y_data
        except (UnicodeDecodeError, pd.errors.EmptyDataError, KeyError):
            continue
    
    raise ValueError(f"Unable to read the file {file_path} with any of the attempted encodings.")
    

    def calculate_mass_loss_at_200(x_data, y_data): initial_mass = y_data.iloc[0] mass_at_200 = np.interp(200, x_data, y_data) mass_loss = initial_mass - mass_at_200 return mass_loss, mass_at_200 # Return both mass loss and mass at 200°C

    def create_graph(files, title): plt.figure(figsize=(18, 10)) # Increased figure width to accommodate larger legends

    mass_loss_labels = []
    vertical_spacing = 10  # Constant space difference for vertical separation
    molecular_weight = 313.7739  # Molecular weight of the compound in g/mol
    molecular_weight_H2O = 18.015  # Molecular weight of water in g/mol
    
    # Keep track of lines and markers for the legend
    lines_for_legend = []
    markers_for_legend = []
    
    for i, file_name in enumerate(files):
        file_path = os.path.join(input_folder, file_name)
        try:
            x_data, y_data = read_data_from_file(file_path)
            label = file_name.replace('.txt', '').replace('!', '')
    
            mass_loss, mass_at_200 = calculate_mass_loss_at_200(x_data, y_data)
            mass_loss_percentage = (mass_loss / y_data.iloc[0]) * 100  # Calculate percentage of mass loss
            
            # Calculate the mass of water based on the mass loss percentage
            mass_of_water = (mass_loss_percentage / 100) * molecular_weight  # Mass of water in grams
            
            # Calculate the number of moles of water
            moles_of_water = mass_of_water / molecular_weight_H2O  # Moles of water
            
            # Format the number of moles for display
            moles_of_water_str = f"{moles_of_water:.2f}"  # Format to two decimal places
    
            # Use a vibrant colormap for distinct colors
            line_color = plt.cm.tab10(i % 10)  # Use the tab10 colormap for colors
            line, = plt.plot(x_data, y_data, label=label, color=line_color)
            lines_for_legend.append(line)
    
            # Mark the point at 200 °C with a smaller symbol
            dot_y_value = np.interp(200, x_data, y_data)
            marker, = plt.plot(200, dot_y_value, marker='o', color=line_color, markersize=5, linestyle='')
            markers_for_legend.append(marker)
    
            # Append the mass loss percentage and number of molecules to the labels
            mass_loss_labels.append(f'{label}: {mass_loss_percentage:.2f}% (≈ {moles_of_water_str} molecules of H₂O)')
    
        except ValueError as e:
            print(f"Error reading {file_name}: {str(e)}")
    
    plt.xlabel('Temperature (°C)', fontsize=12)
    plt.ylabel('Weight (%)', fontsize=12)
    
    # Create the main legend (sample names with circles)
    plt.legend(handles=[plt.Line2D([0], [0], color=line.get_color(), marker='o', markersize=5, label=line.get_label()) 
                        for line, marker in zip(lines_for_legend, markers_for_legend)],
               bbox_to_anchor=(1.05, 0.5), loc='center left', borderaxespad=0., 
               fontsize='medium', frameon=False)
    
    # Add mass loss legend inside the graph on the left with a black square border
    mass_loss_text = "Mass loss\n" + "\n".join(mass_loss_labels)
    plt.text(0.05, 0.5, mass_loss_text, transform=plt.gca().transAxes, 
             verticalalignment='center', fontsize='medium', 
             bbox=dict(boxstyle='square', facecolor='white', edgecolor='black', alpha=0.8))
    
    # Adjust layout to prevent legends from being cut off
    plt.tight_layout()
    plt.subplots_adjust(right=0.8, left=0.1)
    
    output_path = os.path.join(output_folder, f'{title}.png')
    plt.savefig(output_path, dpi=300, bbox_inches='tight')
    plt.close()
    print(f"Graph saved: {output_path}")
    

    Get all txt files in the folder

    txt_files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]

    Categorize files

    h_files = [f for f in txt_files if 'H' in f and not f.startswith('!Mn')] c_files = [f for f in txt_files if 'C' in f] mn_h_files = [f for f in txt_files if 'H' in f and f.startswith('!Mn')]

    Create graphs

    create_graph(h_files, 'H_containing_samples') create_graph(c_files, 'C_containing_samples') create_graph(mn_h_files, 'Mn_H_containing_samples')

    print("All graphs have been created and saved.") print(f"H files: {h_files}") print(f"C files: {c_files}") print(f"Mn-H files: {mn_h_files}")

  2. Assistant

    Yes, it's possible to move the colored points from the general legend to the text within the plot. You can achieve this by creating a custom legend that includes the colored markers and the corresponding text labels (which include the mass loss information). Instead of relying on plt.text() to display the mass loss information, we'll use plt.legend() to create a legend inside the plot area that contains both the markers and the text labels.

    Here's how you can modify your code to achieve this:

    1. Remove the existing general legend and text box: Since we'll be combining these into a single legend inside the plot, you can remove the code that creates the general legend and the plt.text() that displays the mass loss information.

    2. Create handles and labels for the custom legend: In the loop where you're processing each file, collect the legend handles (markers with the appropriate colors) and labels (sample names with mass loss information).

    3. Place the custom legend inside the plot: Use plt.legend() with the collected handles and labels, and adjust its position to where you previously had the text box. You can customize the appearance of the legend to resemble a text box if needed.

    Here's the modified code with the necessary changes:

    import os
    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    # Specify the folder paths
    input_folder = r"C:\Users\samuel.hernandez\OneDrive - FUNDECYT - PCTEX\Escritorio\Doctorado\Experimental\TGA"
    output_folder = r"C:\Users\samuel.hernandez\OneDrive - FUNDECYT - PCTEX\Escritorio\Doctorado\Experimental\TGA\Python\Test"
    
    # Ensure the output folder exists
    os.makedirs(output_folder, exist_ok=True)
    
    def read_data_from_file(file_path):
        encodings = ['utf-8', 'iso-8859-1', 'cp1252']
        for encoding in encodings:
            try:
                data = pd.read_csv(file_path, delim_whitespace=True, skiprows=1, encoding=encoding)
                
                temp_col = data.columns[1]  # Assuming temperature is the second column
                weight_col = data.columns[4]  # Assuming weight is the fifth column
                
                x_data = data[temp_col].str.replace(',', '.').astype(float)
                y_data = data[weight_col].str.replace(',', '.').astype(float)
                
                return x_data, y_data
            except (UnicodeDecodeError, pd.errors.EmptyDataError, KeyError):
                continue
        
        raise ValueError(f"Unable to read the file {file_path} with any of the attempted encodings.")
    
    def calculate_mass_loss_at_200(x_data, y_data):
        initial_mass = y_data.iloc[0]
        mass_at_200 = np.interp(200, x_data, y_data)
        mass_loss = initial_mass - mass_at_200
        return mass_loss, mass_at_200  # Return both mass loss and mass at 200°C
    
    def create_graph(files, title):
        plt.figure(figsize=(18, 10))  # Increased figure width to accommodate larger legends
    
        molecular_weight = 313.7739  # Molecular weight of the compound in g/mol
        molecular_weight_H2O = 18.015  # Molecular weight of water in g/mol
    
        # Keep track of lines and markers for the legend
        legend_handles = []
        legend_labels = []
    
        for i, file_name in enumerate(files):
            file_path = os.path.join(input_folder, file_name)
            try:
                x_data, y_data = read_data_from_file(file_path)
                label = file_name.replace('.txt', '').replace('!', '')
    
                mass_loss, mass_at_200 = calculate_mass_loss_at_200(x_data, y_data)
                mass_loss_percentage = (mass_loss / y_data.iloc[0]) * 100  # Calculate percentage of mass loss
                
                # Calculate the mass of water based on the mass loss percentage
                mass_of_water = (mass_loss_percentage / 100) * molecular_weight  # Mass of water in grams
                
                # Calculate the number of moles of water
                moles_of_water = mass_of_water / molecular_weight_H2O  # Moles of water
                
                # Format the number of moles for display
                moles_of_water_str = f"{moles_of_water:.2f}"  # Format to two decimal places
    
                # Use a vibrant colormap for distinct colors
                line_color = plt.cm.tab10(i % 10)  # Use the tab10 colormap for colors
                plt.plot(x_data, y_data, label=label, color=line_color)
    
                # Mark the point at 200 °C with a smaller symbol
                dot_y_value = np.interp(200, x_data, y_data)
                plt.plot(200, dot_y_value, marker='o', color=line_color, markersize=5, linestyle='')
    
                # Create a handle for the legend entry
                legend_handle = plt.Line2D([0], [0], color=line_color, marker='o', markersize=5, linestyle='')
                legend_handles.append(legend_handle)
    
                # Create the label for the legend entry, including mass loss information
                legend_label = f'{label}: {mass_loss_percentage:.2f}% (≈ {moles_of_water_str} molecules of H₂O)'
                legend_labels.append(legend_label)
    
            except ValueError as e:
                print(f"Error reading {file_name}: {str(e)}")
    
        plt.xlabel('Temperature (°C)', fontsize=12)
        plt.ylabel('Weight (%)', fontsize=12)
    
        # Create a custom legend inside the plot area
        legend = plt.legend(handles=legend_handles, labels=legend_labels, 
                            loc='center left', bbox_to_anchor=(0.05, 0.5), frameon=True, fontsize='medium', 
                            bbox_transform=plt.gca().transAxes)
    
        # Customize legend appearance to resemble a text box
        legend.get_frame().set_facecolor('white')
        legend.get_frame().set_edgecolor('black')
        legend.get_frame().set_linewidth(1.0)
        legend.get_frame().set_alpha(0.8)
    
        # Adjust layout to prevent legends from being cut off
        plt.tight_layout()
        plt.subplots_adjust(right=0.8, left=0.1)
    
        output_path = os.path.join(output_folder, f'{title}.png')
        plt.savefig(output_path, dpi=300, bbox_inches='tight')
        plt.close()
        print(f"Graph saved: {output_path}")
    
    # Get all txt files in the folder
    txt_files = [f for f in os.listdir(input_folder) if f.endswith('.txt')]
    
    # Categorize files
    h_files = [f for f in txt_files if 'H' in f and not f.startswith('!Mn')]
    c_files = [f for f in txt_files if 'C' in f]
    mn_h_files = [f for f in txt_files if 'H' in f and f.startswith('!Mn')]
    
    # Create graphs
    create_graph(h_files, 'H_containing_samples')
    create_graph(c_files, 'C_containing_samples')
    create_graph(mn_h_files, 'Mn_H_containing_samples')
    
    print("All graphs have been created and saved.")
    print(f"H files: {h_files}")
    print(f"C files: {c_files}")
    print(f"Mn-H files: {mn_h_files}")
    

    Explanation of Changes:

    • Removed the existing general legend and text box: The code sections that created the main legend and the plt.text() have been removed to prevent duplicate legends and text within the plot.

    • Collected legend handles and labels: Inside the loop, we created legend_handles and legend_labels lists. For each file, we added a Line2D object (used as a marker in the legend) to legend_handles and the corresponding label (including mass loss information) to legend_labels.

      # Create a handle for the legend entry
      legend_handle = plt.Line2D([0], [0], color=line_color, marker='o', markersize=5, linestyle='')
      legend_handles.append(legend_handle)
      
      # Create the label for the legend entry, including mass loss information
      legend_label = f'{label}: {mass_loss_percentage:.2f}% (≈ {moles_of_water_str} molecules of H₂O)'
      legend_labels.append(legend_label)
      
    • Placed the custom legend inside the plot: We used plt.legend() with the collected legend_handles and legend_labels, placed it inside the plot area at the desired location, and customized its appearance to resemble a text box.

      # Create a custom legend inside the plot area
      legend = plt.legend(handles=legend_handles, labels=legend_labels, 
                          loc='center left', bbox_to_anchor=(0.05, 0.5), frameon=True, fontsize='medium', 
                          bbox_transform=plt.gca().transAxes)
      
      # Customize legend appearance to resemble a text box
      legend.get_frame().set_facecolor('white')
      legend.get_frame().set_edgecolor('black')
      legend.get_frame().set_linewidth(1.0)
      legend.get_frame().set_alpha(0.8)
      
    • Adjusted layout to prevent overlap: We ensured that the legend doesn't overlap with any data in the plot by adjusting the layout.

      # Adjust layout to prevent legends from being cut off
      plt.tight_layout()
      plt.subplots_adjust(right=0.8, left=0.1)
      

    Result:

    With these changes, the plot will display the mass loss information inside the plot area, accompanied by colored markers corresponding to each sample. This effectively moves the colored markers from the general legend to the text within the plot, as per your requirement.

    Feel free to adjust the positioning and styling of the legend to better suit your data and preferences.