【问题标题】:Subplot not working properly子图无法正常工作
【发布时间】:2022-01-25 23:12:08
【问题描述】:

这是我编写的用于生成 2 x 2 子图的代码。

代码如下:

import math
import numpy
import functools
import operator
from fractions import Fraction
import matplotlib.pyplot as plt
import pylab
from pylab import *


def nCk(n, k):
    return int(functools.reduce(operator.mul,
                                (Fraction(n-i, i+1) for i in range(k)), 1))

Theta = 0.5 cList = numpy.arange(-5, 5, 1) NList = [5, 10, 100, 1000]

for i in list(range(len(NList))):
    N = NList[i]
    print(N)
    dList = []

    for c in cList:
        print(c)
        var = math.floor(float(N*Theta) + float(c*Theta*(1-Theta)*math.sqrt(N)))
        dList.append(pow(0.5, N)*(sum(nCk(N, x) for x in range(var))))

    print([1+math.floor(i/2), 1+i % 2])

    # plt.subplot(4,1+math.floor(i/2),1+i%2)
    # plt.plot(cList,dList)
    # plt.title([1+math.floor(i/2),1+i%2])

    subplot(4, 1+math.floor(i/2), 1+i % 2)
    fig = plot(cList, dList)


# plt.savefig('C:/Users/Sumit_G/foo1.png')
pylab.savefig('C:/Users/Sumit_G/foo.png')

但是,不是得到一个 2 x 2 的图。

我得到了下面的数字:

【问题讨论】:

  • 除了您的子图问题之外,您还可以在代码中修复或简化许多事情。例如,在访问数组中的值及其索引时,我们通常会这样做:for i,N in enumerate(NList):。并且有一个用于组合的 scipy 函数(scipy.misc.comb)。而且我相信组合的总和可以简化(从数学上讲),等等......

标签: python matplotlib subplot


【解决方案1】:

您不必要地铺垫和修改您的价值观。子图采用 3 个参数 subplot(nrows, ncols, plot_number) (http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplot),其中 plot_number 是从 1(左上角)开始到 nrows 结束的活动图*ncols(右下)。见附图。

【讨论】:

    【解决方案2】:

    尝试:

        fig = plt.figure()
        for i in range(4):
            ax = fig.add_subplot(2,2,i+1)
            ax.plot(whatever)
    

    【讨论】:

    • 这对我来说是 ovarlapping 所有的情节,至少使用 colab。
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多