在 matplotlib 中添加值和点
add value along with points in matplotlib
我有以下代码段来标记双变量数据分布上的分位数点。三个红点分别对应0.1, 0.5 and 0.9
的分位数。我想添加分位数,即 0.1, 0.5 and 0.9
及其各自的红点。如何在 matplotlib
中执行此操作?
import numpy as np
import matplotlib.pyplot as plt
num_samples = 2000
mu = np.array([5.0, 2.0])
r = np.array([
[ 3.40, -2.75],
[ -2.75, 1.0]
])
rng = np.random.default_rng()
y = rng.multivariate_normal(mu, r, size=num_samples)
quantile_set = np.quantile(y, [0.1,0.5,0.9], axis=0)
plt.plot(y[:,0], y[:,1], 'b.', alpha=0.25)
plt.plot(quantile_set[:,0],quantile_set[:,1],'ro',ms=4.5)
plt.grid(True)
一种可能的解决方案(使用 offset
使文本离点更近或更远):
import numpy as np
import matplotlib.pyplot as plt
num_samples = 2000
mu = np.array([5.0, 2.0])
r = np.array([
[ 3.40, -2.75],
[ -2.75, 1.0]
])
rng = np.random.default_rng()
y = rng.multivariate_normal(mu, r, size=num_samples)
quantile_set = np.quantile(y, [0.1,0.5,0.9], axis=0)
plt.figure()
plt.plot(y[:,0], y[:,1], 'b.', alpha=0.25)
plt.plot(quantile_set[:,0],quantile_set[:,1],'ro',ms=4.5)
qtexts = [0.1, 0.5, 0.9]
offset = np.array([
abs(y[:, 0].min() - y[:, 0].max()) * 0.05,
abs(y[:, 1].min() - y[:, 1].max()) * 0.05
])
for q, t in zip(quantile_set, qtexts):
plt.text(*(q+offset), t, color="r", horizontalalignment="right", verticalalignment="top")
plt.grid(True)
我有以下代码段来标记双变量数据分布上的分位数点。三个红点分别对应0.1, 0.5 and 0.9
的分位数。我想添加分位数,即 0.1, 0.5 and 0.9
及其各自的红点。如何在 matplotlib
中执行此操作?
import numpy as np
import matplotlib.pyplot as plt
num_samples = 2000
mu = np.array([5.0, 2.0])
r = np.array([
[ 3.40, -2.75],
[ -2.75, 1.0]
])
rng = np.random.default_rng()
y = rng.multivariate_normal(mu, r, size=num_samples)
quantile_set = np.quantile(y, [0.1,0.5,0.9], axis=0)
plt.plot(y[:,0], y[:,1], 'b.', alpha=0.25)
plt.plot(quantile_set[:,0],quantile_set[:,1],'ro',ms=4.5)
plt.grid(True)
一种可能的解决方案(使用 offset
使文本离点更近或更远):
import numpy as np
import matplotlib.pyplot as plt
num_samples = 2000
mu = np.array([5.0, 2.0])
r = np.array([
[ 3.40, -2.75],
[ -2.75, 1.0]
])
rng = np.random.default_rng()
y = rng.multivariate_normal(mu, r, size=num_samples)
quantile_set = np.quantile(y, [0.1,0.5,0.9], axis=0)
plt.figure()
plt.plot(y[:,0], y[:,1], 'b.', alpha=0.25)
plt.plot(quantile_set[:,0],quantile_set[:,1],'ro',ms=4.5)
qtexts = [0.1, 0.5, 0.9]
offset = np.array([
abs(y[:, 0].min() - y[:, 0].max()) * 0.05,
abs(y[:, 1].min() - y[:, 1].max()) * 0.05
])
for q, t in zip(quantile_set, qtexts):
plt.text(*(q+offset), t, color="r", horizontalalignment="right", verticalalignment="top")
plt.grid(True)