Skip to content

[Bug]: legend and actual colors in plot are inverted #28348

@JosephBARBIERDARNAL

Description

@JosephBARBIERDARNAL

Bug summary

I'm not sure if it's a bug or just me not using the functions well enough, but I think that when I add a colour bar or create a legend, the colors are "inverted" (see the plots below) and therefore unreliable.

Code for reproduction

import matplotlib.cm as cm
import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

data = gpd.read_file('https://raw.githubusercontent.com/JosephBARBIERDARNAL/misc-dataviz/main/country-co2/data.geojson')
# load the colormap
cmap = cm.Greens
background_color = 'white'
text_color = 'black'

# legend values
value_ranges = [0, 2, 4, 6, 8, 10, 12]
labels = ['0-2 t', '2-4 t', '4-6 t', '6-8 t', '8-10 t', '10-12 t', '12+ t']
def create_legend_elements(cmap, value_ranges, labels):
    legend_elements = []
    n = len(value_ranges)
    for i in range(n-1):
        value = (value_ranges[i] + value_ranges[i+1]) / 2 / value_ranges[-1]  # Normalize the value to [0, 1]
        legend_elements.append(Patch(facecolor=cmap(value), label=labels[i]))
    return legend_elements
legend_elements = create_legend_elements(cmap, value_ranges, labels)

# initialize the figure
fig, ax = plt.subplots(figsize=(10, 10), dpi=300)
fig.set_facecolor(background_color)

# create the plot
data.plot(ax=ax, cmap=cmap, edgecolor='black', linewidth=0.5)

# annot norway and sweden
norway = data.loc[data['country'] == 'Norway']['co2Capita'].values[0]
sweden = data.loc[data['country'] == 'Sweden']['co2Capita'].values[0]
fig.text(0.35, 0.67, f'Norway: {norway}', fontsize=8, fontweight='bold', color='black')
fig.text(0.45, 0.62, f'Sweden: {sweden}', fontsize=8, fontweight='bold', color='black')

# custom axis
ax.set_xlim(-11, 41)
ax.set_ylim(32, 73)
ax.set_axis_off()

# add the patches to the plot area as a legend
rectangle_width = 2
rectangle_height = 1.5
legend_x = 35
legend_y_start = 65
legend_y_step = 1.5
for i, element in enumerate(legend_elements):
    ax.add_patch(plt.Rectangle((legend_x, legend_y_start - i * legend_y_step), rectangle_width, rectangle_height,
                               color=element.get_facecolor(), ec='black'))
    ax.text(legend_x + 2.5, legend_y_start - i * legend_y_step + 0.7, element.get_label(), 
            fontsize=12, color=text_color, va='center')
    
# add colorbar
cax = inset_axes(ax, width='5%', height='50%', loc='center left')
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=0, vmax=12))
sm._A = []
cbar = plt.colorbar(sm, cax=cax)
                 
plt.show()

Actual outcome

Screenshot 2024-06-05 at 15 33 38

Expected outcome

Screenshot 2024-06-05 at 15 34 59

Additional information

don't know any fix or why is that behaviour happening.

Operating system

macOS sonoma 14.5

Matplotlib Version

3.9.0

Matplotlib Backend

module://matplotlib_inline.backend_inline

Python version

3.10.5

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions