【问题标题】:Error passing function to pyplot将函数传递给 pyplot 时出错
【发布时间】:2014-09-07 07:24:15
【问题描述】:

我创建了一个 Python 2.7 脚本,该脚本使用 Monte Carlo 方法计算 pi。然后我尝试使用 pyplot 在半对数图上创建 pi 值的图。这是我的代码:

from numpy.random import rand, seed
import matplotlib.pyplot as plt

## Initialize the random number generator with seed value of 1
seed(1)

## Set the dimensions of the square and circle and the total number of cycles
sq_side = 1.0
radius = 1.0
cycles = 1000000
total_area = sq_side**2

## The main function
def main():
    # Initialize a few variables and the X,Y lists for the graph
    i = 0
    N = 0
    Y = []
    X = []
    while not N == cycles:
        # Generate random numbers and test if they are in the circle
        x,y = rand(2, 1)
        if x**2 + y**2 <= 1.0:
            i += 1
        # Calculate pi on each cycle
        quarter_circle_area = total_area * i / cycles
        calculated_pi = 4 * quarter_circle_area / radius**2
        # Add the value of pi and the current cycle number to the X,Y lists
        Y.append(calculated_pi)
        X.append(N)
        N += 1
    return X, Y

## Plot the values of pi on a logarithmic scale x-axis
ax = plt.subplot(111)
ax.set_xscale('log')
ax.set_xlim(0, 1e6)
ax.set_ylim(-4, 4)
ax.scatter(main())

plt.show()

很遗憾,我收到以下错误消息:

Traceback (most recent call last):
  File "C:/Users/jonathan/PycharmProjects/MonteCarlo-3.4/pi_simple.py", line 45, in <module>
    ax.scatter(main())
TypeError: scatter() takes at least 3 arguments (2 given)

我在this post 中查看了 Matthew Adams 的解释,但似乎无法理解这个问题。任何帮助将不胜感激。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您需要在传递它们之前将main 创建的列表元组解压缩为单独的参数ax.scatter

    x, y = main()
    ax.scatter(x, y)
    

    或使用“splat”解包语法:

    ax.scatter(*main())
    

    另一个参数,带你到三个,是实例方法的隐式第一个 self 参数。

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多