在 python 中编辑标记形状
Edit marker shape in python
我在 CDF 图的 x 轴上使用菱形指针来显示某些数据的分布。由于数据量大,这些点靠得很近,无法区分。我想知道是否有办法让散点图的菱形标记更 pointy.
您可以从路径定义自己的标记,请参阅 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)
虽然我喜欢@Stef 关于创建新标记符号的回答,但您也可以根据与其他点的距离调整现有符号的大小:
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 in zip(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)
我使用了 scikit-learn 的 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 是一个关于 scatter()
中标记大小参数的小教程。
我在 CDF 图的 x 轴上使用菱形指针来显示某些数据的分布。由于数据量大,这些点靠得很近,无法区分。我想知道是否有办法让散点图的菱形标记更 pointy.
您可以从路径定义自己的标记,请参阅 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)
虽然我喜欢@Stef 关于创建新标记符号的回答,但您也可以根据与其他点的距离调整现有符号的大小:
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 in zip(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)
我使用了 scikit-learn 的 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 是一个关于 scatter()
中标记大小参数的小教程。