[PYTHON] How to plot a lot of legends by changing the color of the graph continuously with matplotlib

I want to change the color with matplotlib and display a lot of legends

Usage

I want to display a lot of graphs using matplotlib, but by default I can only get a finite number of colors. I would like to introduce an easy way to solve this. In that case, I often want to display a lot of legends, which was difficult with the old matplotlib, but now it's very easy, so I'll show you how to do it as a bonus.

sample

Overview

For the two functions y = arctan ((n + 1) x) and y = x ^ n, we will introduce an example of overlaying a graph with n shifted by 20.

colormap points

usercmap = plt.get_cmap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=num)
scalarMap = cm.ScalarMappable(norm=cNorm, cmap=usercmap)

Now select jet with colormap, declare color coding with 0 to num (20) number of data, and generate scalarMap with cm.ScalarMappable. In the for loop Select a color as c = scalarMap.to_rgba (i).

Points for displaying a lot of legends

python


plt.legend(bbox_to_anchor=(0., 1.01, 1., 0.01), loc='lower left',ncol=10, mode="expand", borderaxespad=0.,fontsize=8)

Specify the location with bbox_to_anchor = (X coordinate, Y coordinate, X size, Y size), and adjust the number of columns to fold with ncol.

Sample code

python



#!/usr/bin/env python 
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'serif'
import optparse
import matplotlib.pylab as plab
from matplotlib.colors import LogNorm
import matplotlib.colors as colors

### plot 1D plot : shifted 
F = plt.figure(figsize=(12,8.))
plt.subplots_adjust(wspace=0.3, hspace=0.6)

ax = plt.subplot(2,1,1)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)             
plt.figtext(0.02,0.02,"[matplotlib legend test]")
plt.xscale('linear')
plt.yscale('linear')
plt.grid(linestyle='dotted',alpha=0.5)
plt.xlabel(r'x-axis (a.u.)')
plt.ylabel(r'y-axis')        
x = np.arange(-1,1,0.1)
num=20
y = []
for j in range(num):
    y.append(np.arctan(x*(j+1)))

usercmap = plt.get_cmap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=num)
scalarMap = cm.ScalarMappable(norm=cNorm, cmap=usercmap)

for i,oney in enumerate(y):
    c = scalarMap.to_rgba(i)
    plt.errorbar(x, oney, fmt="o-", color = c, alpha = 0.8, linewidth = 1, label=str(i))        

plt.legend(bbox_to_anchor=(0., 1.01, 1., 0.01), loc='lower left',ncol=10, mode="expand", borderaxespad=0.,fontsize=8)


ax = plt.subplot(2,1,2)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)             
plt.xscale('linear')
plt.yscale('linear')
plt.grid(linestyle='dotted',alpha=0.5)
plt.xlabel(r'x-axis (a.u.)')
plt.ylabel(r'y-axis')        
x = np.arange(-1,1,0.1)
num=20
y = []
for j in range(num):
    y.append(np.power(x,j+1))

usercmap = plt.get_cmap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=num)
scalarMap = cm.ScalarMappable(norm=cNorm, cmap=usercmap)

for i,oney in enumerate(y):
    c = scalarMap.to_rgba(i)
    plt.errorbar(x, oney, fmt="o-", color = c, alpha = 0.8, linewidth = 1, label=str(i))        

plt.legend(bbox_to_anchor=(-0.1, 1.0, 1.2, 0.01), loc='lower left',ncol=10, mode="expand", borderaxespad=0.,fontsize=8)

plt.savefig("qiita_legend_sample.png ")
plt.show()


Click here for the generated figure.

qiita_legend_sample.png

Notes

It's now easier to expand the legend horizontally and display it outside the graph, but the expand option only supports horizontal, not vertical (as of 2019.1.8). I think time will be settled.

Recommended Posts

How to plot a lot of legends by changing the color of the graph continuously with matplotlib
How to avoid the cut-off label of the graph created by the plot module using matplotlib
[Python] How to draw a line graph with Matplotlib
Paste a link to the data point of the graph created by jupyterlab & matplotlib
[Python] How to draw a scatter plot with Matplotlib
Continuously color with matplotlib scatter plot
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to draw a bar graph that summarizes multiple series with matplotlib
How to calculate the volatility of a brand
How to draw a 2-axis graph with pyplot
Increase the font size of the graph with matplotlib
How to display images continuously with matplotlib Note
The basis of graph theory with matplotlib animation
[python] How to sort by the Nth Mth element of a multidimensional array
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
Add information to the bottom of the figure with Matplotlib
How to create a submenu with the [Blender] plugin
[Python] Summary of how to specify the color of the figure
How to add color bars in matplotlib bar plot
[Python] How to create a 2D histogram with Matplotlib
Display the graph while changing the parameters with PySimpleGUI + Matplotlib
Try to create a battle record table with matplotlib from the data of "Schedule-kun"
How to identify the element with the smallest number of characters in a Python list?
[Ruby] How to replace only a part of the string matched by the regular expression?
A memo on how to overcome the difficult problem of capturing FX with AI
[Ubuntu] How to delete the entire contents of a directory
[Python] How to make a list of character strings character by character
How to test the attributes added by add_request_method of pyramid
Reformat the timeline of the pandas time series plot with matplotlib
How to display a list of installable versions with pyenv
A story about how to deal with the CORS problem
How to plot the distribution of bacterial composition from Qiime2 analysis data in a box plot
Create a 2D array by adding a row to the end of an empty array with numpy
[Graph drawing] I tried to write a bar graph of multiple series with matplotlib and seaborn
How to insert a specific process at the start and end of spider with scrapy
How to connect the contents of a list into a string
How to send a file in one shot by connecting to a host on the other side of the platform with SCP in multiple stages
When generating a large number of graphs with matplotlib, I do not want to display the graph on the screen (jupyter environment)
I want to create a graph with wavy lines omitted in the middle with matplotlib (I want to manipulate the impression)
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
How to display the CPU usage, pod name, and IP address of a pod created with Kubernetes
[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
How to determine the existence of a selenium element in Python
[Statistics] Grasp the image of the central limit theorem with a graph
[Introduction to Python] How to split a character string with the split function
How to change the color of just the button pressed in Tkinter
How to check the memory size of a variable in Python
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
How to make a command to read the configuration file with pyramid
Here's a brief summary of how to get started with Django
How to check the memory size of a dictionary in Python
[TensorFlow 2] How to check the contents of Tensor in graph mode
How to find the memory address of a Pandas dataframe value
Count the maximum concatenated part of a random graph with NetworkX
How to output the output result of the Linux man command to a file
How to monitor the execution status of sqlldr with the pv command
How to get the vertex coordinates of a feature in ArcPy
How to send a request to the DMM (FANZA) API with python
[NNabla] How to remove the middle tier of a pre-built network