Home > Net >  add value along with points in matplotlib
add value along with points in matplotlib

Time:04-30

I have the following code segment to mark the quantile points on a bivariate data distribution. The three red points correspond to quantiles of 0.1, 0.5 and 0.9 respectively. I would like to add the quantile value, i.e., 0.1, 0.5 and 0.9 along with their respective red points. How to do this in 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)

enter image description here

CodePudding user response:

One possible solution (play with offset to get the texts closer or far away from the points):

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)

enter image description here

  • Related