简体   繁体   中英

Custom legend format for Matplotlib scatterplot

I am plotting multiple datasets from several dataframes using matplotlib.pyplot using the following code:

import matplotlib.pyplot as plt

def plot_deltas(dfs, labels):
    
    labels = iter(labels)
    
    markers = iter(['o', 's', 'D'])
    colors = iter(['blue', 'red', 'green'])
    
    fig, ax = plt.subplots()
    ax.set_ylabel(r"$\Delta\delta_{iso}^{C-M}$ (ppm)", fontsize=14)
    
    for df in dfs:
        marker = next(markers)
        color = next(colors)
        label = next(labels)
        line1, = ax.plot(df['label'], df['delta_c-m_a'], color=color, linewidth=0, fillstyle='full', marker=marker, markeredgewidth=2.0, label=label+" A")
        line2, = ax.plot(df['label'], df['delta_c-m_b'], color=color, linewidth=0, fillstyle='none', marker=marker, markeredgewidth=2.0, label=label+" B")
        
    plt.grid(axis='x')
    plt.legend(fontsize=12)
    
    return fig, ax

Calling plot_deltas([df1, df2, df3], ['Form I', 'Form II', 'Form III']) returns the plot:

在此处输入图像描述

Instead of this bulky legend, I would like to create something that looks more like this:

在此处输入图像描述

How can I customize the format of the legend simply? I've searched through the documentation for Matplotlib, but I haven't found anything quite like this.

You can use plt.text() (matplotlib.axes.Axes.text) instead of the legend method. Check the many examples linked at the bottom of the webpage.

Here's a great answer . I've modified your code based on that answer. However, you cannot insert a slash between the handlers. The labels are a list with 'A/B' added to the string obtained from the arguments.

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple

def plot_deltas(dfs, labels):
    
    labels = iter(labels)
    
    markers = iter(['o', 's', 'D'])
    colors = iter(['blue', 'red', 'green'])
    
    fig, ax = plt.subplots()
    ax.set_ylabel(r"$\Delta\delta_{iso}^{C-M}$ (ppm)", fontsize=14)
    
    new_handles = []
    new_labels = []
    for df in dfs:
        marker = next(markers)
        color = next(colors)
        label = next(labels)
        line1, = ax.plot(df['label'], df['delta_c-m_a'], color=color, linewidth=0, fillstyle='full', marker=marker, markeredgewidth=2.0, label=label+" A")
        line2, = ax.plot(df['label'], df['delta_c-m_b'], color=color, linewidth=0, fillstyle='none', marker=marker, markeredgewidth=2.0, label=label+" B")
        n_h = (line1, line2)
        new_handles.append(n_h)
        n_l = '{}{}'.format(label, ' A / B')
        new_labels.append(n_l)
        
    plt.grid(axis='x')
    plt.legend(new_handles, new_labels, handler_map={tuple: HandlerTuple(ndivide=2)},handlelength=3,fontsize=12)
    return fig, ax

plot_deltas([df1, df2, df3], ['Form I', 'Form II', 'Form III'])

plt.show()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM