matplotlib 如何在转换数据后根据原始数据更改轴线限制

iyfjxgzm  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(106)

我有下面的代码,问题是我想保持x限制为原始数据(failure)和y数据之间的0,1,或0,99.9999%。我想这样做,而不使用twinx轴:

import numpy as np
import matplotlib.pyplot as plt 

#data
failure = np.array([168, 202, 190, 197, 169, 214, 201, 219, 206, 198, 190, 183, 206, 218, 214, 206, 213, 202, 209, 206])

#get plotting position for pprbablity distribution plots
def plottingPositionOriginal(failure, a=0.3):
    x = np.sort(failure)
    n = len(x)
    F = []
    for i in range(1, len(failure)+1):
        F.append((i - a) / (n + 1 - 2 * a))
    
    y = np.array(F)
    return x, y

# transform the y axis so the plot appears linear
def plottingPositionFit(failure):
    t, F = plottingPositionOriginal(failure)
    x = np.log(t)
 
    y = np.log(-np.log(1 - F))
    beta, c = np.polyfit(x, y, 1)
    y_fit = beta * x + c

    return x, y, y_fit

X, Y, y_hat = plottingPositionFit(failure)

fig, ax = plt.subplots()
ax.scatter(X, Y) 

ax.plot(X, y_hat) 

plt.show()

这是我目前的情节:

这就是我想要的情节(减去红线):

tjvv9vkg

tjvv9vkg1#

您可以将数据以原始形式提供给Matplotlib,并为每个轴指定尺度以指定转换:对于x轴,内置的对数尺度就足够了;对于y轴,您可以创建自定义尺度。在这里,我通过定义y_forwardy_inverse来实现这一点。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, MaxNLocator

#data
failure = np.array([168, 202, 190, 197, 169, 214, 201, 219, 206, 198, 190, 183, 206, 218, 214, 206, 213, 202, 209, 206])

# Define forward and inverse transformations for the y-axis
def y_forward(val):
    return np.log(-np.log(1 - val))

def y_inverse(val):
    return 1 - np.exp(-np.exp(val))

#get plotting position for pprbablity distribution plots
def plottingPositionOriginal(failure, a=0.3):
    x = np.sort(failure)
    n = len(x)
    F = []
    for i in range(1, len(failure)+1):
        F.append((i - a) / (n + 1 - 2 * a))
    
    y = np.array(F)
    return x, y

# transform the y axis so the plot appears linear
def plottingPositionFit(failure):
    t, F = plottingPositionOriginal(failure)
    x = np.log(t)
 
    y = y_forward(F)
    beta, c = np.polyfit(x, y, 1)
    y_fit = beta * x + c
    F_fit = y_inverse(y_fit)

    return t, F, F_fit

X, Y, y_hat = plottingPositionFit(failure)

fig, ax = plt.subplots()
ax.scatter(X, Y) 
ax.set_xscale("log")
ax.xaxis.set_minor_formatter(ScalarFormatter())
ax.set_yscale("function", functions=(y_forward, y_inverse))
ax.yaxis.set_major_locator(MaxNLocator(10))

ax.plot(X, y_hat) 

plt.show()

相关问题