2016-06-10 99 views
1

我用matplotlib绘制两行文字,并希望标记最大的改进。我用ax.annotate,得到了以下不希望的结果,如何标记matplotlib中两行之间的百分比变化?

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() 

是否有更好的方法,以纪念两行之间的百分比变化?

回答

1

我同意@ hobenkr。您必须在另外两个注释a上分割您的注释:第一个是箭头,第二个是文本标签。对于文字你可以设置bold的重量。

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 

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

# add annotate to arrow 
ax1.annotate(improvements, 
    xy=(x_max, y1_max + .3 * (y2_max-y1_max)), xycoords='data', 
    xytext=(-50, 0), textcoords='offset points', color='r', weight='bold', size=10) 

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

plt.show() 

enter image description here

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()