Matplotlib:在图表上的每个点旁边显示值

zu0ti5jz  于 2023-05-23  发布在  其他
关注(0)|答案(3)|浏览(161)

是否可以在图表上显示每个点的值:

点上显示的值为:[7,57,121,192,123,240,546]

values = list(map(lambda x: x[0], result)) #[7, 57, 121, 192, 123, 240, 546]
labels = list(map(lambda x: x[1], result)) #['1950s', '1960s', '1970s', '1980s', '1990s', '2000s', '2010s']

plt.plot(labels, values, 'bo')
plt.show()

这是我目前的代码为这个图表。
我想知道图上显示的每个点的值,目前我只能预测基于y轴的值。

1qczuiv0

1qczuiv01#

根据您的值,这里有一个使用plt.text的解决方案

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
values = [7, 57, 121, 192, 123, 240, 546]
labels = ['1950s', '1960s', '1970s', '1980s', '1990s', '2000s', '2010s']

plt.plot(range(len(labels)), values, 'bo') # Plotting data
plt.xticks(range(len(labels)), labels) # Redefining x-axis labels

for i, v in enumerate(values):
    ax.text(i, v+25, "%d" %v, ha="center")
plt.ylim(-10, 595)
plt.show()

输出

carvr3hs

carvr3hs2#

基于plt.annotate的解决方案

fig = plt.figure()
ax = fig.add_subplot(111)
values = [7, 57, 121, 192, 123, 240, 546]
labels = ['1950s', '1960s', '1970s', '1980s', '1990s', '2000s', '2010s']

plt.plot(range(len(labels)), values, 'bo') # Plotting data
plt.xticks(range(len(labels)), labels) # Redefining x-axis labels

for i, v in enumerate(values):
    ax.annotate(str(v), xy=(i,v), xytext=(-7,7), textcoords='offset points')
plt.ylim(-10, 595)

输出:

dzjeubhm

dzjeubhm3#

好吧,对于任何需要更复杂一点的东西的人,这里是@Sheldore对我自己的数据的回答的扩展:

如何使用plt.text()绘制每个点的(x, y)文本,并使用自定义文本格式处理第一个和最后一个点:
import matplotlib.pyplot as plt

from statistics import mean

# cluster size (KiB) vs speed (MB/s)
x_cluster_size = [0.5, 4, 8, 32, 128, 32768]
y_speed = [
    mean([87.36, 96.84]),
    mean([285.36, 352.37, 309.35]),
    mean([333.19, 320.87, 360.62]),
    mean([360.59, 329.26, 387.60]),
    mean([392.01, 363.88, 413.63]),
    mean([437.09, 409.12, 436.98]),
]
plt.plot(x_cluster_size, y_speed, 'b-o', label='When writing a 5.3 GB file')
plt.legend(loc='lower right')
plt.xscale('log', base=2)
plt.ylabel('Speed (MB/sec)')
plt.xlabel('exFAT cluster size (KiB)')
plt.title("exFAT cluster size vs speed")
# display (x, y) values next to each point
for i, x in enumerate(x_cluster_size):
    y = y_speed[i]
    # first element
    if i == 0:
        plt.text(x+.2, y, f"({x} KiB, {y:.0f} MB/sec)", horizontalalignment="left")
    # last element
    elif i == len(x_cluster_size) - 1:
        plt.text(x-10000, y, f"({x} KiB, {y:.0f} MB/sec)", horizontalalignment="right")
    else:
        plt.text(x, y-20, f"({x} KiB, {y:.0f} MB/sec)", horizontalalignment="left")
plt.show()

相关问题