简体   繁体   中英

How to display a y value on each point in a plot?

I'm drawing this multi graph and would like to show the y value on each point.

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0, 1])
y1 = np.array([float(2.396), float(2.339)])
y2 = np.array([float(1.500), float(1.460)])
y3 = np.array([float(1.067), float(0.933)])
y4 = np.array([float(0.800), float(0.800)])
y5 = np.array([float(0.076), float(0.067)])
y = (float(2.396), float(2.339), float(1.500), float(1.460), float(1.067), float(0.933), float(0.800), float(0.800),
     float(0.076), float(0.067))
my_xticks = ['I1', 'I2']
plt.xticks(x, my_xticks)
plt.plot(x, y1, marker='o', markerfacecolor='blue', markersize=12, color='blue', linewidth=2)
plt.plot(x, y2, marker='o', markerfacecolor='olive', markersize=12, color='olive', linewidth=2)
plt.plot(x, y3, marker='o', markerfacecolor='red', markersize=12, color='red', linewidth=2)
plt.plot(x, y4, marker='o', markerfacecolor='skyblue', markersize=12, color='skyblue', linewidth=2)
plt.plot(x, y5, marker='o', markerfacecolor='green', markersize=12, color='green', linewidth=2)
plt.grid(True, linestyle="--", color='black')
plt.show()

我的阴谋

Matplotlib's annotate provides a lot of functionality to add text to a plot, optionally including an arrow. Note that matplotlib doesn't search for an optimal position to place the text, you need to provide x,y position (in the coordinates of the axes of the plot) and an optional offset (in pixel coordinates) to position the text.

An example:

import matplotlib.pyplot as plt
import numpy as np

xs = np.array([0, 1])
y2 = np.array([1.500, 1.460])
y3 = np.array([1.067, 0.933])
y1 = np.array([2.396, 2.339])
y4 = np.array([0.800, 0.800])
y5 = np.array([0.076, 0.067])
plt.xticks(xs, ['I1', 'I2'])
for ys, color in zip([y1, y2, y3, y4, y5], ['blue', 'olive', 'red', 'skyblue', 'green']):
    plt.plot(xs, ys, marker='o', markerfacecolor=color, markersize=5, color=color, linewidth=2)
    for x, y in zip(xs, ys):
        plt.annotate(y,
                     xy=(x, y),
                     xytext=(15 if x == 0 else -15, -20 if y > 2 or y == 0.8 else 10),
                     textcoords='offset points',
                     arrowprops=dict(facecolor='black', arrowstyle='->'),
                     horizontalalignment='left' if x == 0 else 'right',
                     verticalalignment='bottom')
plt.grid(True, linestyle="--", color='black')
plt.show()

示例图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM