为什么灰色条和上限箭头宽度之间存在偏移

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

对于下图,它显示了两个变量 X 和 Y 之间的红色箭头上限,右侧有 Z 轴显示灰色条的值,为什么它们在灰色条和箭头宽度之间存在偏移。

Image showing arrows offset from bars

该图的完整代码如下所示:

def plot(Xmin, Xmax):
    
    datafile = ''  # Placeholder for the data file path

    try:
        data = np.loadtxt(datafile)
        xmin = data[:, 0]
        xmax = data[:, 1]
        yvalue = data[:, 2]
        yerror = data[:, 3]
        zvalue = data[:, 4]
        upperBound = data[:, 5]

        # Compute the midpoint of the x-axis
        x = np.sqrt(xmin * xmax)
        xerr = np.array([x - xmin, xmax - x])

        # Compute y-axis values
        y = x**2 * yvalue / (xmax - xmin)
        yerr = x**2 * yerror / (xmax - xmin)
        y_ul = x**2 * upperBound / (xmax - xmin)
        y_ulerr = np.array([0.5 * y_ul, [0] * len(y)])

        # Create the plot
        fig, ax = plt.subplots()

        # Plot the data points where z > 9
        ax.errorbar(x[zvalue > 9], y[zvalue > 9], xerr=xerr[:, zvalue > 9], yerr=yerr[zvalue > 9], 
                    fmt='.k', color='blue', label='Detected', markersize=12)

        # Plot upper limits where z < 9, in red
        ax.errorbar(x[zvalue < 9], y_ul[zvalue < 9], xerr=xerr[:, zvalue < 9], yerr=y_ulerr[:, zvalue < 9], 
                    fmt='.k', color='red', uplims=True, label='Upper Limit', markersize=12)

        # Set axis limits and scales
        ax.set_xlim(a,b)
        ax.set_ylim(c, d)
        ax.set_xscale('log')
        ax.set_yscale('log')

        # Set axis labels with bold font
        ax.set_xlabel(r'X [units]', fontweight='bold')
        ax.set_ylabel(r'Y [units]', fontweight='bold', fontsize=9)

        # Plot z-values on a secondary axis
        ax2 = ax.twinx()
        ax2.bar(x, zvalue, width=(xmax - xmin), color='gray', edgecolor='gray', alpha=0.5)
        ax2.set_ylim(bottom=0)
        ax2.set_xscale('log')
        ax2.set_ylabel('Z value', fontweight='bold')

        # Return the file paths (placeholders)
        return png_file, pdf_file

    except Exception as e:
        print(f"An error occurred: {e}")

我预计灰色条和红色箭头宽度之间不会有任何偏移。与几何平均数有关吗?或者 matplotlib 绘图中有一些错误。我尝试使用算术平均值,但那里没有偏移。造成这个问题的原因可能是什么?

python python-3.x matplotlib plot visualization
1个回答
0
投票

我认为问题是在 matplotlib 中的 bar 命令中,宽度围绕中心对称。换句话说,如果条形的中心位于 x 处,则边缘位于 x-width/2 和 x+width/2 处。而这里的中心不是对称的。有没有办法在 matplotlib 中获得不对称条形图?

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