小能豆

Python Matplotlib 图表 X 轴显示范围不正确

py

由于代码有很多行,我首先要展示一下问题所在:

1.png

我定义了一个简单的循环并得到了适当的结果。

2.png

在这里,当我尝试使用 matplotlib 绘制它时,x 轴上显示的范围与我输入的范围不同。我想要 0 到 100,步长为 5,但我得到的是 0 到 17.5,步长为 2.5。

我这样编码有什么问题吗?如果没有,下面是其余代码,谢谢!:

import random
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from matplotlib.colors import ListedColormap
import sys
import decimal 
sys.setrecursionlimit(4000)

n = 10   # number of rows and columns in the grid
p = 0.9  # probability that each square is open

def gridMakerN(n):
  grid = (np.random.rand(n,n) < p).astype(int)
  mycolormap = ListedColormap(["grey","blue"])
  #plt.imshow(grid, cmap=mycolormap)
  return grid

# define an exception that we will raise if percolation is detected
class percolationException(Exception): pass

# query() looks for a path from (row, col) to the bottom of the grid
# recursive function: it calls itself to determine if a path exists
def query(row, col, grid, visited):
  #print("Visiting square ", row, ",", col) <- This was previously part of the code

  # mark row, col as visited
  visited[row,col] = 1

  # is row equal to the bottom row? If so, output "path found"
  (numRows,numCols) = np.shape(grid)
  if row == numRows - 1:
    #print("PERCOLATION FOUND!!!") <- This was previously part of the code
    raise percolationException

  else:
    # if square below is open and unvisited, then is there a path from that square?
    if grid[row+1,col] == 1 and visited[row+1,col] == 0:
      query(row+1, col, grid, visited)

    # if square at left is open and unvisited, then is there a path from that square?
    if col > 0 and grid[row, col-1] == 1 and visited[row, col-1] == 0:
      query(row, col-1, grid, visited)

    # if square at right is open and unvisited, then is there a path from that square?
    if col+1 < numCols and grid[row, col+1] == 1 and visited[row, col+1] == 0:
      query(row, col+1, grid, visited)

    # if square above is open and unvisited, then is there a path from that square?
    if row > 0 and grid[row-1, col] == 1 and visited[row-1, col] == 0:
      query(row-1, col, grid, visited)


# driver function to manage the whole percolation detection process
def findPercolation(grid):

  # create an empty visited matrix
  (numRows, numCols) = np.shape(grid)
  visited = np.zeros( (numRows, numCols) )

  # look for a percolation path, starting at each open square in the top row
  try:
    for c in range(numCols):     # consider all squares in the top row
      if grid[0,c] == 1:
        query(0, c, grid, visited)

  except percolationException:
    #print("percolationException occurred") <- This was previously part of the code
    return 1 # <- Here I put 1 instead of "True"

  else:
    #print("percolation not found") <- This was previously part of the code
    return 0 # <- Here I put 0 instead of "False"

def findPercolationFixedP(n):
  return findPercolation(gridMakerN(n))

def percAvgFixedP(n):
  iterations = 100
  results = [] #Making an Empty List
  for _ in range(iterations): #Repeat the Same Step x times
    results.append(findPercolationFixedP(n))
    #print(results)
    #print(sum(results))
  return sum(results)/iterations

def avgFixedPGraph():
  results = []
  for x in range(10,100,5):
    results.append(percAvgFixedP(x))
  plt.plot(results,"c")
  plt.grid()
  plt.show()

avgFixedPGraph()

阅读 16

收藏
2024-12-06

共1个答案

小能豆

plot()仅给出一个数组时:

plt.plot(results, "c")

该数组被视为值yx值默认为数字范围。在本例中results,有 18 个值,因此绘制范围x从 0 到 17。

要分配自定义x值,请明确传递它们,例如:

x = range(10, 100, 5)
results = [percAvgFixedP(value) for value in x]
plt.plot(x, results, "c")
2024-12-06