如何在matplotlib中标记两行之间的百分比变化?

时间:2016-06-10 21:39:49

标签: python matplotlib annotations

我使用matplotlib绘制两行,并希望标记最大的改进。我使用ax.annotate并得到以下不良结果,

enter image description here

这是源代码。

from __future__ import division
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2)

x = range(10)
y1 = range(10)
y2 = [2*i for i in range(10)]

# plot line graphs
ax1.plot(x, y1)
ax1.plot(x, y2)

# the maximum improvements
x_max = max(x)
y1_max = max(y1)
y2_max = max(y2)
improvements = "{:.2%}".format((y2_max-y1_max)/y1_max) # percentage


ax1.annotate(improvements,
            xy=(x_max, y2_max), xycoords='data',
            xytext=(x_max, y1_max), textcoords='data', color='r',
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color='r'))

# for showing the expected result
ax2.plot(x, y1)
ax2.plot(x, y2)

plt.show()

有没有更好的方法来标记两行之间的百分比变化?

2 个答案:

答案 0 :(得分:2)

我会将文字和箭头拆分成单独的部分。

#!/bin/python

from __future__ import division
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2)

x = range(10)
y1 = range(10)
y2 = [2*i for i in range(10)]

# plot line graphs
ax1.plot(x, y1)
ax1.plot(x, y2)

# the maximum improvements
x_max = max(x)
y1_max = max(y1)
y2_max = max(y2)
improvements = "{:.2%}".format((y2_max-y1_max)/y1_max) # percentage

ax1.arrow(x_max, y1_max, 0, y2_max-y1_max, width=0.1, head_width=0.5, head_length=0.5, color='r', length_includes_head=True)

ax1.annotate('100.00', xy=(x_max-2, y2_max-y1_max+3), fontsize=10, color='r')

# for showing the expected result
ax2.plot(x, y1)
ax2.plot(x, y2)

plt.show()

答案 1 :(得分:1)

我同意@hobenkr。您必须在另外两个注释上拆分注释:第一个是箭头,第二个是文本标签。对于文字,您可以设置foo[[[["bar"]]]] === foo[[[["bar"]]].toString()] === foo["bar"] 重量。

bold

enter image description here