Skip to content Skip to sidebar Skip to footer

Edit Marker Shape In Python

I'm using diamond pointer on the x-axis of a CDF plot to show the distribution of some data. As the number of data is high, these points are close together and not distinguishable.

Solution 1:

While I like @Stef's answer of creating new marker symbols, you can also just adjust the size of existing symbols with regard to their distance to other points:

import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import NearestNeighbors

# create random data
x = np.random.rand(10)
y = np.ones(len(x))

# open figure + axes
fig,axs = plt.subplots(1,2)
# standard scatter-plot
MarkerSize = 40
axs[0].scatter(x,y,s=MarkerSize)

# re-arrange data
xy = []
for x1,y1 inzip(x,y):
    xy.append([x1,y1])
# find nearest neighbors to itself (skip the first column because it finds the exact same element, i.e. with zero distance)
dst,idx = NearestNeighbors(n_neighbors=2).fit(xy).kneighbors(xy)
dst = dst[:,1]

# create a vector for the marker-size
S = dst/dst.max()*MarkerSize
# scatter plot with adjusted marker-size
axs[1].scatter(x,y,s=S)

enter image description here

I used scikit-learn's sklearn.neighbors.NearestNeighbors() to calculate the smallest distance between points and pass this as a scaling factor to the size-argument s= of matplotlib.pyplot.scatter(). There is a little tutorial for the marker-size argument in scatter().

Solution 2:

You can define your own markers from a path, see the Marker Path Example.

import matplotlib.pyplot as plt
import matplotlib.path as mpath

pointed_diamond = mpath.Path([[0,-.5],[-.1,0],[0,.5],[.1,0],[0,-.5]], [1,2,2,2,79])
plt.plot([1,2,3], marker=pointed_diamond, markersize=10)

enter image description here

Post a Comment for "Edit Marker Shape In Python"