ValueError:行数必须是正整数,而不是 3.0

Pre*_*Ven 3 python statistics matplotlib scipy

我有这个代码:

\n
import numpy as np\nfrom scipy import stats\nfrom matplotlib import pyplot as plt\n\nif __name__ == "__main__":\n    # Create a list of the number of coin tosses ("Bernoulli trials")\n    number_of_trials = [0, 2, 10, 20, 50, 500]\n    # Conduct 500 coin tosses and output into a list of 0s and 1s\n    # where 0 represents a tail and 1 represents a head\n    data = stats.bernoulli.rvs(0.5, size=number_of_trials[-1])\n    # Discretise the x-axis into 100 separate plotting points\n    x = np.linspace(0, 1, 100)\n    # Loops over the number_of_trials list to continually add\n    # more coin toss data. For each new set of data, we update\n    # our (current) prior belief to be a new posterior. This is\n    # carried out using what is known as the Beta-Binomial model.\n    # For the time being, we won\xe2\x80\x99t worry about this too much.\n    for i, N in enumerate(number_of_trials):\n        # Accumulate the total number of heads for this\n        # particular Bayesian update\n        heads = data[:N].sum()\n        # Create an axes subplot for each update\n        ax = plt.subplot(len(number_of_trials) / 2, 2, i + 1)\n    \n        ax.set_title("%s trials, %s heads" % (N, heads))\n        # Add labels to both axes and hide labels on y-axis\n        plt.xlabel("$P(H)$, Probability of Heads")\n        plt.ylabel("Density")\n        if i == 0:\n            plt.ylim([0.0, 2.0])\n            plt.setp(ax.get_yticklabels(), visible=False)\n\n            # Create and plot a Beta distribution to represent the\n            # posterior belief in fairness of the coin.\n            y = stats.beta.pdf(x, 1 + heads, 1 + N - heads)\n            plt.plot(x, y, label="observe %d tosses,\\n %d heads" % (N, heads))\n            plt.fill_between(x, 0, y, color="#aaaadd", alpha=0.5)\n            # Expand plot to cover full width/height and show it\n            plt.tight_layout()\n            plt.show()\n
Run Code Online (Sandbox Code Playgroud)\n

我在这一行收到错误:ax = plt.subplot(len(number_of_trials) / 2, 2, i + 1) \nValueError: Number of rows must be a positive integer, not 3.0

\n

我尝试设置int(number_of_trials)但没有成功。

\n

有任何想法吗?

\n

Muh*_*han 5

您需要将整体投射len(number_of_trials) / 2int.

ax = plt.subplot(int(len(number_of_trials) / 2), 2, i + 1)
Run Code Online (Sandbox Code Playgroud)

这解决了错误。