Split marker and line in Legend - Matplotlib

2024/10/18 15:00:56

I want to make a legend where I specify the value for the markers and the value for the lines but not the combination of both.

This example should help to illustrate my goal:

import matplotlib.pyplot as plt
import numpy as nppi=3.14
xx=np.linspace(0,2*pi,100)fig = plt.figure()
ax  = fig.add_subplot(111)phases=[0,pi/4,pi/2]
markers=['s','o','^']for phase,mk in zip(phases,markers):labeltext='Sine' + '*' + str(phase)F=[np.sin(x+phase) for x in xx]ax.plot(xx,F,color='b',marker=mk,label=labeltext)labeltext='Cosine' + '*' + str(phase)F=[np.cos(x+phase) for x in xx]ax.plot(xx,F,color='g',marker=mk,label=labeltext)hand, labl = ax.get_legend_handles_labels()
#hand, labl = function_to_split(hand,labl,'*')
ax.legend(hand,labl)
plt.savefig('Figure.png')

The resulting figure is the following MWE figure

What I wanted is a function_to_split to automatically end up with a legend like this:

[blue line] Sine
[green line] Cosine
[black square] 0
[black circle] 0.785
[black triangle] 1.57
Answer

I figured it out by automatically creating fictitious handles.

import matplotlib.pyplot as plt
import numpy as npdef function_to_split(hand,labl,dividor):Hand_L=[]Hand_M=[]Labl_L=[]Labl_M=[]for h,l in zip(hand,labl):co=h.get_color()ls=h.get_linestyle()lw=h.get_linewidth()mk=h.get_marker()mew=h.get_markeredgewidth()ms=h.get_markersize()LABS=l.split(dividor)if len(LABS) != 2:print 'Split Legends Error: Only exactly 1 Dividor is accepted.'print '                     Currently ' + str(len(LABS)-1) + ' dividors were given'return hand,labl#Line and ColorLICO = plt.Line2D((0,1),(0,0), color=co, marker='', linestyle=ls,linewidth=lw)#MarkerMARK = plt.Line2D((0,1),(0,0), color='k', marker=mk, markeredgewidth=mew, markersize=ms, linestyle='')if LABS[0] not in Labl_L:Hand_L.append(LICO)Labl_L.append(LABS[0])if LABS[1] not in Labl_M:Hand_M.append(MARK)Labl_M.append(LABS[1])return Hand_L+Hand_M,Labl_L+Labl_Mpi=3.14
xx=np.linspace(0,2*pi,100)fig = plt.figure()
ax  = fig.add_subplot(111)phases=[0,pi/4,pi/2]
markers=['s','o','^']for phase,mk in zip(phases,markers):labeltext='Sine' + '*' + str(phase)F=[np.sin(x+phase) for x in xx]ax.plot(xx,F,color='b',marker=mk,label=labeltext)labeltext='Cosine' + '*' + str(phase)F=[np.cos(x+phase) for x in xx]ax.plot(xx,F,color='g',marker=mk,label=labeltext)hand, labl = ax.get_legend_handles_labels()
hand, labl = function_to_split(hand,labl,'*')
ax.legend(hand,labl)
plt.savefig('Figure.png')

enter image description here

https://en.xdnf.cn/q/72837.html

Related Q&A

How do I loop over all items in a DynamoDB table using boto?

Id like to query a DynamoDB table and retrieve all the items and loop over them using boto. How do I structure a query or scan that returns everything in the table?

install pyopencv with pip on Mac OS X

I am trying to install pyopencv with pip in OS X Mountain Lion and it fails by import setuptools. Following is my work. what is "Library" in setuptools? I have not seen that before. I alread…

OpenCV remap interpolation error?

Im using opencv remap function to map an image to another coordinate system. However, my initial tests indicate that there are some issues with the interpolation. Here, I give a simple example of a co…

Installing python with python win32 extensions on a network drive

I need to keep a large number of Windows XP machines running the same version of python, with an assortment of modules, one of which is python-win32. I thought about installing python on a network dri…

Python pytest hangs. For instance, pytest --version simply hangs

The following hangs:PS C:\Users\Fowler> pytest --version Notes:I am in Windows 10. By hang, I mean at least 5 minutes of waiting for the pytest --version to return... While waiting for pytest, pyth…

PyQt4 signals and slots

I am writing my first Python app with PyQt4. I have a MainWindow and a Dialog class, which is a part of MainWindow class:self.loginDialog = LoginDialog();I use slots and signals. Heres a connection mad…

Masking a pandas DataFrame with a numpy array vs DataFrame

I want to use a 2D boolean mask to selectively alter some cells in a pandas DataFrame. I noticed that I cannot use a numpy array (successfully) as the mask, but I can use a DataFrame. More frustratin…

How to explode multiple columns, different types and different lengths?

Ive got a DF with columns of different time cycles (1/6, 3/6, 6/6 etc.) and would like to "explode" all the columns to create a new DF in which each row is a 1/6 cycle.from pyspark import Row…

How to convert \xXY encoded characters to UTF-8 in Python?

I have a text which contains characters such as "\xaf", "\xbe", which, as I understand it from this question, are ASCII encoded characters. I want to convert them in Python to their…

Pandas One hot encoding: Bundling together less frequent categories

Im doing one hot encoding over a categorical column which has some 18 different kind of values. I want to create new columns for only those values, which appear more than some threshold (lets say 1%), …