Matplotlib 不能一致地使用 plt.xscale('log') 转换绘制的元素

问题描述 投票:0回答:1

绘制数据时,matplotlib 错误地转换了垂直线。对于线性 x 轴,我的曲线和指向曲线上特定位置的垂直线完美匹配。 Vertical line touching curve as expected 在 plt.xscale('log') 之后,垂直线的终点不再位于我的曲线上。 Second screenshot after log transform

import numpy as np
import matplotlib.pyplot as plt

# Generate example data: x values from 1 to 16 (log scale)
x = np.array([1, 2, 4, 8, 16])
y = np.array([0.1, 0.2, 0.3, 0.6, 0.9])

# Perform linear interpolation to find where y crosses 0.5
crossings = np.where(np.diff(np.sign(y - 0.5)))[0]

if len(crossings) > 0:
    crossing_index = crossings[0]
    x1, x2 = x[crossing_index], x[crossing_index + 1]
    y1, y2 = y[crossing_index], y[crossing_index + 1]
    
    # Linear interpolation to find exact x for y = 0.5
    x_nd50 = x1 + (0.5 - y1) * (x2 - x1) / (y2 - y1)
    
    print(f"Interpolated x (ND50) = {x_nd50}")

# Plot the data with a logarithmic x scale
plt.plot(x, y, label="Data", color="blue")

# Plot the vertical line at the interpolated ND50 value
plt.plot([x_nd50, x_nd50], [0, 0.5], color='red', linestyle="--", alpha=0.7)
plt.scatter(x_nd50, 0.5, color='red', marker='x', alpha=0.7)

# First screenshot taken at this point!

# Set x-axis to log scale (log2)
plt.xscale('log')

# Second screenshot taken at this point!

# Show the plot
plt.xlabel('Log-scaled X')
plt.ylabel('Y')
plt.legend()
plt.show()

matplotlib transform scale logarithm
1个回答
0
投票

您可以按如下方式解决:

[...]

xlog = True
# Perform linear interpolation to find where y crosses 0.5
crossings = np.where(np.diff(np.sign(y - 0.5)))[0]

if len(crossings) > 0:
    crossing_index = crossings[0]
    x1, x2 = x[crossing_index], x[crossing_index + 1]
    y1, y2 = y[crossing_index], y[crossing_index + 1]

    if xlog:
        x1 = np.log10(x1)
        x2 = np.log10(x2)
    # Linear interpolation to find exact x for y = 0.5
    x_nd50 = x1 + (0.5 - y1) * (x2 - x1) / (y2 - y1)
    if xlog:
        x_nd50 = 10**x_nd50
    print(f"Interpolated x (ND50) = {x_nd50}")

[...]

# Set x-axis to log scale (log2)
if xlog:
    plt.xscale('log')

[...]
© www.soinside.com 2019 - 2024. All rights reserved.