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

Use the subset data and extent with applied mask img2 = ax2.imshow(temperaturesubset,…

  1. User

    Use the subset data and extent with applied mask

    img2 = ax2.imshow(temperature_subset, extent=extent_subset, origin='upper',
                    cmap=cmap, norm=norm, alpha=1)
    
    # Plot hillshade on top using subset data with mask
    # ax2.imshow(hs_subset, extent=extent_subset, cmap='gray', origin='upper', alpha=0.3)
    
    # Overlay water bodies using subset data with mask
    # ax2.imshow(water_mask_subset, extent=extent_subset, origin='upper', cmap='Blues', alpha=0.5)
    
    # Plot clipped Masovian boundary with a light, dark stroke
    masovian_boundary_clipped.boundary.plot(ax=ax2, edgecolor='#333333', linewidth=1.5)
    
    # Plot stations within the bounding box
    stations_in_bbox.plot(ax=ax2, color='black', marker='s', markersize=5)
    
    # Remove axes for a minimalistic look
    ax2.axis('off')
    
    # Introduce a subtle background gradient using the subset extent
    ax2.imshow(
        np.linspace(0, 1, 256).reshape(1, -1),
        cmap=background_cmap,
        extent=extent_subset,
        aspect='auto',
        alpha=0.2,
        zorder=-1  # Place it below other elements
    )
    
    # Adjust font properties for a modern look
    plt.rcParams.update({
        'font.size': 14,
        'font.family': 'sans-serif',
        'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
        'text.color': '#333333'
    })
    
    # Enlarge and reposition the product name (Title)
    fig2.text(
        0.5, 0.995,  # Moved up towards the top edge
        "High-Resolution Mesoscale Temperature Analysis",
        fontsize=12,
        fontweight='bold',
        ha='center',
        va='top',
        fontname='DejaVu Sans',
        color='#333333'
    )
    
    # Move the model name/resolution text closer to the product name text
    fig2.text(
        0.5, 0.970,  # Moved up slightly below the title
        "Model: HRMTA v1.1 (Preview)   |   Resolution: 250 m",
        fontsize=9,
        ha='center',
        va='top',
        fontname='DejaVu Sans',
        color='#666666'
    )
    
    # Add data source attribution at the bottom left corner
    fig2.text(
        0.01, 0.02,
        "Data source: IMGW-PIB (processed)",
        fontsize=12,
        ha='left',
        va='bottom',
        fontname='DejaVu Sans',
        color='#333333'
    )
    
    # Adjust colorbar position and style
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    divider = make_axes_locatable(ax2)
    cax2 = divider.append_axes("right", size="3%", pad=0.1)
    cbar2 = fig2.colorbar(img2, cax=cax2)
    cbar2.set_ticks(ticks)
    cbar2.set_ticklabels(ticks.astype(int))
    
    # Import FontProperties and load the font
    from matplotlib.font_manager import FontProperties
    
    # Replace 'input/RobotoCondensed-Regular.ttf' with the actual path to your font file
    roboto_font_path = 'input/RobotoCondensed-Regular.ttf'
    roboto_condensed = FontProperties(fname=roboto_font_path)
    
    # Apply font properties to the colorbar tick labels
    for label in cbar2.ax.yaxis.get_ticklabels():
        label.set_fontproperties(roboto_condensed)
    
    cbar2.ax.tick_params(labelsize=14)
    
    # Enhance colorbar aesthetics
    cbar2.outline.set_visible(False)
    cbar2.ax.yaxis.set_tick_params(width=0.5)
    cbar2.ax.tick_params(labelsize=14, colors='#333333')
    
    # Move the logo to the bottom right corner, directly below the colorbar
    from matplotlib.offsetbox import OffsetImage, AnnotationBbox
    import matplotlib.image as mpimg
    
    # Read the logo image again for the second plot
    logo_img2 = mpimg.imread(logo_path)
    
    # Adjust the size of the logo
    imagebox2 = OffsetImage(logo_img2, zoom=logo_zoom)
    
    # Get the position of the colorbar axes
    cbar_bbox2 = cax2.get_position()
    logo_x2 = (cbar_bbox2.x0 + cbar_bbox2.x1) / 2
    logo_y2 = 0.02  # Adjust this value if necessary
    
    ab2 = AnnotationBbox(
        imagebox2,
        xy=(logo_x2, logo_y2),
        xycoords='figure fraction',
        frameon=False,
        box_alignment=(0.5, 0),
    )
    fig2.add_artist(ab2)
    
    # Adjust the bottom margin to ensure the logo and data attribution text are not cut off
    plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.06)
    
    # Ensure the temperature grid and water mask are aligned
    if temperature_with_ecostress.shape != water_mask.shape:
        raise ValueError("Temperature grid and water mask dimensions do not match.")
    
    # Create a masked array for land temperatures by excluding water bodies within the subset
    temperature_land_subset = temperature_subset.copy()
    if not isinstance(temperature_land_subset, np.ma.MaskedArray):
        temperature_land_subset = np.ma.array(temperature_land_subset)
    temperature_land_subset.mask = temperature_land_subset.mask | (water_mask_subset == 1)
    
    # Calculate minimum temperature over land within the subset
    min_temp = temperature_land_subset.min()
    
    # Calculate maximum temperature within the subset (including all areas)
    max_temp = temperature_subset.max()
    
    # Get the indices of the min and max temperatures within the subset
    min_indices_flat = np.ma.argmin(temperature_land_subset)
    max_indices_flat = np.ma.argmax(temperature_subset)
    min_indices = np.unravel_index(min_indices_flat, temperature_land_subset.shape)
    max_indices = np.unravel_index(max_indices_flat, temperature_subset.shape)
    
    # Convert grid indices to geographic coordinates using the new_transform (subset transform)
    min_lon_full, min_lat_full = rasterio.transform.xy(new_transform, min_indices[0], min_indices[1])
    max_lon_full, max_lat_full = rasterio.transform.xy(new_transform, max_indices[0], max_indices[1])
    
    # Add contours to the plot using the subset data
    min_temp_c = np.floor(min_temp)
    max_temp_c = np.ceil(max_temp)
    contour_levels = np.arange(min_temp_c, max_temp_c + 1, 1)
    
    contours = ax2.contour(
        temperature_subset, levels=contour_levels, colors='black', linewidths=0.5,
        extent=extent_subset, origin='upper'
    )
    contour_labels = ax2.clabel(
        contours, inline=False, fontsize=8, fmt='%d', colors='white',
        inline_spacing=4, manual=False
    )
    for txt in contour_labels:
        txt.set_path_effects([
            patheffects.Stroke(linewidth=3, foreground='black'),
            patheffects.Normal()
        ])
    
    # Now add the min/max temperature labels after the contours and contour labels
    text_kwargs = dict(
        fontsize=18,
        fontname='Arial',
        ha='center',
        va='center',
        color='white',
        transform=ax2.transData,
        path_effects=[patheffects.withStroke(linewidth=3, foreground='black')]
    )
    
    # Format temperature values with one decimal point
    ax2.text(min_lon_full, min_lat_full, f"{min_temp:.1f}", **text_kwargs)
    ax2.text(max_lon_full, max_lat_full, f"{max_temp:.1f}", **text_kwargs)
    
    # Reverse geocode min and max temperature locations to find nearest village
    from geopy.geocoders import Nominatim
    geolocator = Nominatim(user_agent="geoapiExercises")
    
    try:
        min_location = geolocator.reverse((min_lat_full, min_lon_full), language='en')
        min_address = min_location.raw.get('address', {})
        min_village = min_address.get('village', 
                        min_address.get('town', 
                        min_address.get('city', 'Unknown Location')))
    except Exception as e:
        print(f"Error reverse geocoding min location: {e}")
        min_village = 'Unknown Location'
    
    try:
        max_location = geolocator.reverse((max_lat_full, max_lon_full), language='en')
        max_address = max_location.raw.get('address', {})
        max_village = max_address.get('village', 
                        max_address.get('town', 
                        max_address.get('city', 'Unknown Location')))
    except Exception as e:
        print(f"Error reverse geocoding max location: {e}")
        max_village = 'Unknown Location'
    
    if not (np.isnan(min_lat_full) or np.isnan(min_lon_full)):
        min_village = get_village_name(min_lat_full, min_lon_full)
        min_label_text = f"MIN:\n {min_temp:.1f}°C: {min_village}"
    else:
        min_label_text = f"MIN:\n {min_temp:.1f}°C: Unknown Location"
        print("Minimum temperature location coordinates are invalid.")
    
    if not (np.isnan(max_lat_full) or np.isnan(max_lon_full)):
        max_village = get_village_name(max_lat_full, max_lon_full)
        max_label_text = f"MAX:\n {max_temp:.1f}°C: {max_village}"
    else:
        max_label_text = f"MAX:\n {max_temp:.1f}°C: Unknown Location"
        print("Maximum temperature location coordinates are invalid.")
    
    # Define font properties
    from matplotlib.font_manager import FontProperties
    roboto_font_path = 'input/RobotoCondensed-Regular.ttf'
    roboto_condensed = FontProperties(fname=roboto_font_path)
    
    # Add minimum temperature label to the figure
    fig2.text(
        0.02, 0.95, min_label_text,
        ha='left', va='top',
        fontsize=16,  # Increased font size
        fontproperties=roboto_condensed,
        color='#ADD8E6',  # Light Blue
        weight='bold',  # Bold font weight
        path_effects=[patheffects.withStroke(linewidth=2, foreground='black')]
    )
    
    # Add maximum temperature label to the figure, moved further downward
    fig2.text(
        0.98, 0.90, max_label_text,  # Further lowered y-coordinate
        ha='right', va='top',
        fontsize=16,  # Increased font size
        fontproperties=roboto_condensed,
        color='#F08080',  # Light Coral
        weight='bold',  # Bold font weight
        path_effects=[patheffects.withStroke(linewidth=2, foreground='black')]
    )
    
    # Save and show the plot
    plt.savefig('output/temperature_analysis_with_contours2.png', dpi=300)
    plt.show()
    
    print("Temperature analysis plot with contours created successfully.")
    
    # At the end, print feature importances to confirm MODIS influence
    print("\nFeature importances from the Random Forest model:")
    print(feature_importances_df)
    

    Check if 'Distance_to_Water' has significant importance

    distance_water_importance = feature_importances_df.loc[feature_importances_df['Feature'] == 'Distance_to_Water', 'Importance'].values[0]
    if distance_water_importance > 0.05:  # Threshold can be adjusted
        print(f"\n'Distance_to_Water' feature has significant influence on the model (importance: {distance_water_importance:.4f}).")
    else:
    

    Here, I want the max village temp text be displayed right under the min temp text, not in the other part of the plot. Additionally, after the "MAX:" text the other part of the text is being slightly displaced to the right, not like the MIN text which is displayed correctly with the second text starting right under the MIN:. And additionally, I want MIN: and MAX: text to stay white, while the village and temperature value should stay the same colour the entire text is coloured by now.

  2. Assistant

    To achieve your desired outcomes, we need to make a few adjustments to your code:

    1. Move the MAX temperature label under the MIN temperature label: We'll position both labels on the left side of the plot, with the MAX label placed directly below the MIN label.

    2. Align the text properly after "MAX:": We'll remove any leading spaces and ensure that the text alignment is consistent for both labels.

    3. Set "MIN:" and "MAX:" to white while keeping the temperature and village names in their respective colors: We'll split the labels into two parts—one for "MIN:"/"MAX:" in white and bold, and another for the temperature and village name in color.

    Here's the adjusted code:

    # Define font properties
    from matplotlib.font_manager import FontProperties
    roboto_font_path = 'input/RobotoCondensed-Regular.ttf'
    roboto_condensed = FontProperties(fname=roboto_font_path)
    
    # Set initial positions
    x_label = 0.02
    y_min_label = 0.95
    delta_y = 0.08  # Adjust this value to control the spacing between labels
    
    # Add MIN label "MIN:" in white
    fig2.text(
        x_label, y_min_label, "MIN:",
        ha='left', va='top',
        fontsize=16,
        fontproperties=roboto_condensed,
        color='white',
        weight='bold',
        path_effects=[patheffects.withStroke(linewidth=2, foreground='black')]
    )
    
    # Add MIN temperature and village in light blue
    fig2.text(
        x_label, y_min_label - 0.04, f"{min_temp:.1f}°C: {min_village}",
        ha='left', va='top',
        fontsize=16,
        fontproperties=roboto_condensed,
        color='#ADD8E6',  # Light Blue
        path_effects=[patheffects.withStroke(linewidth=2, foreground='black')]
    )
    
    # Add MAX label "MAX:" in white, positioned below the MIN label
    fig2.text(
        x_label, y_min_label - delta_y, "MAX:",
        ha='left', va='top',
        fontsize=16,
        fontproperties=roboto_condensed,
        color='white',
        weight='bold',
        path_effects=[patheffects.withStroke(linewidth=2, foreground='black')]
    )
    
    # Add MAX temperature and village in light coral
    fig2.text(
        x_label, y_min_label - delta_y - 0.04, f"{max_temp:.1f}°C: {max_village}",
        ha='left', va='top',
        fontsize=16,
        fontproperties=roboto_condensed,
        color='#F08080',  # Light Coral
        path_effects=[patheffects.withStroke(linewidth=2, foreground='black')]
    )
    

    Explanation:

    • Positioning: We're using the same x_label for both the MIN and MAX labels to align them on the left side. We calculate the y positions to place the MAX label right below the MIN label.

    • Text Alignment: We've removed any leading spaces in the temperature and village texts to ensure proper alignment under "MIN:" and "MAX:".

    • Coloring: By splitting each label into two parts, we can assign white color to "MIN:" and "MAX:" while keeping the temperature and village names in their respective colors.

    • Font and Effects: We've maintained the font properties and path effects to ensure consistency and readability.

    Note: Adjust the delta_y and the value subtracted for the temperature and village text (0.04 in the example) to fine-tune the spacing based on your specific figure size and layout.

    This will result in both the MIN and MAX labels appearing on the left side of the plot, properly aligned, with "MIN:" and "MAX:" in white and bold, and the remaining text in color.