Can I pass a list of colors for points to matplotlibs Axes.plot()?

2024/10/18 15:28:14

I've got a lot of points to plot and am noticing that plotting them individually in matplotlib takes much longer (more than 100 times longer, according to cProfile) than plotting them all at once.

However, I need to color code the points (based on data associated with each one) and can't figure out how to plot more than one color for a given call to Axes.plot(). For example, I can get a result similar to the one I want with something like

fig, ax = matplotlib.pyplot.subplots()
rands = numpy.random.random_sample((10000,))
for x in range(10000):ax.plot(x, rands[x], 'o', color=str(rands[x]))
matplotlib.pyplot.show()

but would rather do something much faster like

fig, ax = matplotlib.pyplot.subplots()
rands = numpy.random.random_sample((10000,))
# List of colors doesn't work
ax.plot(range(10000), rands, 'o', color=[str(y) for y in rands])
matplotlib.pyplot.show()

but providing a list as the value for color doesn't work in this way.

Is there a way to provide a list of colors (and for that matter, edge colors, face colors , shapes, z-order, etc.) to Axes.plot() so that each point can potentially be customized, but all points can be plotted at once?


Using Axes.scatter() seems to get part way there, since it allows for individual setting of point color; but color is as far as that seems to go. (Axes.scatter() also lays out the figure completely differently.)

Answer

It is about 5 times faster for me to create the objects (patches) directly. To illustrate the example, I have changed the limits (which have to be set manually with this method). The circle themselves are draw with matplotlib.path.Path.circle. Minimal working example:

import numpy as np
import pylab as plt
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollectionfig, ax = plt.subplots(figsize=(10,10))
rands = np.random.random_sample((N,))patches = []
colors  = []for x in range(N):C = Circle((x/float(N), rands[x]), .01)colors.append([rands[x],rands[x],rands[x]])patches.append(C)plt.axis('equal')
ax.set_xlim(0,1)
ax.set_ylim(0,1)collection = PatchCollection(patches)
collection.set_facecolor(colors)
ax.add_collection(collection)
plt.show()

enter image description here

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

Related Q&A

Tidy data from multilevel Excel file via pandas

I want to produce tidy data from an Excel file which looks like this, with three levels of "merged" headers:Pandas reads the file just fine, with multilevel headers:# df = pandas.read_excel(t…

ttk tkinter multiple frames/windows

The following application I have created is used to demonstrate multiple windows in tkinter. The main problem is that none of the Entry controls, neither in the bmi-calculator or the converter, accept …

input() vs sys.stdin.read()

import sys s1 = input() s2 = sys.stdin.read(1)#type "s" for examples1 == "s" #False s2 == "s" #TrueWhy? How can I make input() to work properly? I tried to encode/decode…

Renormalize weight matrix using TensorFlow

Id like to add a max norm constraint to several of the weight matrices in my TensorFlow graph, ala Torchs renorm method.If the L2 norm of any neurons weight matrix exceeds max_norm, Id like to scale it…

Numpy: find the euclidean distance between two 3-D arrays

Given, two 3-D arrays of dimensions (2,2,2):A = [[[ 0, 0],[92, 92]],[[ 0, 92],[ 0, 92]]]B = [[[ 0, 0],[92, 0]],[[ 0, 92],[92, 92]]]How do you find the Euclidean distance for each vector in A and B e…

Is it possible to break from lambda when the expected result is found

I am Python newbie, and just become very interested in Lambda expression. The problem I have is to find one and only one target element from a list of elements with lambda filter. In theory, when the t…

Intersection of multiple pandas dataframes

I have a number of dataframes (100) in a list as:frameList = [df1,df2,..,df100]Each dataframe has the two columns DateTime, Temperature.I want to intersect all the dataframes on the common DateTime col…

docker with pycharm 5

I try to build a docker-based development box for our django app. Its running smoothly.None of my teammembers will care about that until there is a nice IDE integration, therefore I play the new and sh…

How to make a simple Python REST server and client?

Im attempting to make the simplest possible REST API server and client, with both the server and client being written in Python and running on the same computer.From this tutorial:https://blog.miguelgr…

Histogram fitting with python

Ive been surfing but havent found the correct method to do the following.I have a histogram done with matplotlib:hist, bins, patches = plt.hist(distance, bins=100, normed=True)From the plot, I can see …