如何写出直线图上点的精确值?

2024-05-14 12:53:29 发布

您现在位置:Python中文网/ 问答频道 /正文

import matplotlib.pyplot as plt

objects = ('A', 'B', 'C')
avgA, avgB, avgC = 0.009990256984352774, 0.0014206548643907065, 0.055161861569464204
performance = [avgA, avgB, avgC]
exact = plt.plot(performance, alpha=0.5, color= 'purple')
plt.xlabel('Compression Method')
plt.ylabel('Average Distance b/w Uncompressed & Compressed Point')
plt.title('Evaluation of Different Compression Methods - Averages')
plt.tight_layout()
plt.show()

我的图表有3个问题:

  1. 我希望X轴标签是A,B&;C而不是0.0、1.0和;2.0. y轴上的值正确

  2. 如何在A/B/C的折线图上显示精确值?例如,x轴上的A对应于y轴上的0.00999,但在图上,精确值不会写入任何位置。就像在条形图中一样,我们可以在条形图的顶部写下值。我们能对线图这样做吗

  3. 另外,我如何提高评分?当前,我的图形显示的y轴值从0.0到0.5,但我希望使其更精确。 enter image description here


Tags: importalphaobjectsplotmatplotlibasperformanceplt
1条回答
网友
1楼 · 发布于 2024-05-14 12:53:29

要设置xtick,最好只调用plot,将objects作为其第一个参数。要设置更多的y记号,MultipleLocator可以用来指示主记号和次记号之间的距离(主记号显示一个数字)

要向绘图添加文本,只需调用plt.annotate('text', xy=(x,y)),其中x是0、1、2,因为x只是标签。y是通常的y值。 您可以添加许多选项来定位文本,有无箭头、对齐等。请参见documentation

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

avgA, avgB, avgC = 0.009990256984352774, 0.0014206548643907065, 0.055161861569464204
objects = ('A', 'B', 'C')
performance = [avgA, avgB, avgC]
plt.plot(objects, performance, alpha=0.5, color= 'purple')
plt.plot(objects, performance, color= 'dodgerblue', marker='o')
ax = plt.gca()
ax.yaxis.set_major_locator(MultipleLocator(0.005))
ax.yaxis.set_minor_locator(MultipleLocator(0.001))
for i, avg in enumerate(performance):
    plt.annotate('%0.5f' % avg, xy=(i, avg), color='dodgerblue', xytext=(7, 2), textcoords='offset points')
plt.xlim(-0.1, 2.35) # set xlims to make place for the text
plt.xlabel('Compression Method')
plt.ylabel('Average Distance b/w Uncompressed & Compressed Point')
plt.title('Evaluation of Different Compression Methods - Averages')
plt.tight_layout()
plt.show()

example plot

相关问题 更多 >

    热门问题