为了从x 和y 坐标迭代绘制散点图,这两个迭代必须具有相同的长度。如果 x 可迭代对象比 y 长,那么应该给出额外的 x 值的 y 坐标是多少(反之亦然)?
import random
import matplotlib.pyplot as plt
num1 = 30
num3 = [4000,3000,1500,9000,2500,8000,1200,800,900,1000,5400,9500,1100,3400,8100,
5500,1200,3830,2311,9999]
num2_array = []
for _ in num3:
num2 = random.randrange(0,45)
print(num2)
num2_array.append(num2)
plt.axvline(num1,0,color="r")
plt.scatter(num2_array,num3,marker=",")
plt.show()
现在可以正常工作了,但是 numpy 使用 numpy.random.random_integers 函数为我们提供了一种更好(更快、更清晰等)的方法。
import random
import matplotlib.pyplot as plt
import numpy as np
num1 = 30
num3 = [4000,3000,1500,9000,2500,8000,1200,800,900,1000,5400,9500,1100,3400,8100,
5500,1200,3830,2311,9999]
num2_array = np.random.random_integers(0,45,len(num3))
plt.axvline(num1,0,color="r")
plt.scatter(num2_array,num3,marker=",")
plt.show()
要计算红线左侧的点,您可以简单地执行以下操作:
count = 0
for value in num2_array:
if value <= num1:
count += 1
要在绘图上写下这个计数,您需要查看 matplotlib 的 annotating plots 的各种方法。您可以使用 text 方法绘制计数文本,并告诉 matplotlib 使用轴坐标系,使其始终绘制在左上角。您还需要 annotate 函数来使用箭头绘制注释。下面是一个完整的例子
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
fig = plt.figure()
ax = fig.add_subplot(111)
num1 = 30
num3 = [4000,3000,1500,9000,2500,8000,1200,800,900,1000,5400,9500,1100,3400,8100,
5500,1200,3830,2311,9999]
num2_array = np.random.random_integers(0,45,len(num3))
count = 0
for value in num2_array:
if value <= num1:
count += 1
ax.axvline(num1,0,color="r")
ax.scatter(num2_array,num3,marker=",")
ax.text(x=0.85,y=0.95,s="Count: {}".format(count), transform=ax.transAxes)
ax.annotate("Text", xy=(num1, max(num3)/2), xytext=(num1*1.2, (max(num3)/2)*1.2), arrowprops=dict(facecolor='black'))
plt.show()