Search code examples
pythonmatplotlibplot

LogLog plot with errors in matplotlib


I want to get plot in LogLog scale with errors. What i should to fix here? As far as I understand, the ability to add errors is not built into loglog method.

x = np.arange(182).astype('float64')
y = np.arange(182).astype('float64')
yerr = np.arange(182).astype('float64')
with open("/home/erg/ch5", "r") as myfiley:
    datay = myfiley.read().splitlines()
with open("/home/erg/ch6", "r") as myfilex:
     datax = myfilex.read().splitlines()
 with open("/home/erg/ch4", "r") as myfilez:
     dataz = myfilez.read().splitlines()
for i in range(len(datax)):
    x[i] = datax[i]
    y[i] = datay[i]
    yerr[i] = dataz[i]
fig, ax = plt.subplots(figsize=(8, 6))
ax.tick_params(axis='both', labelsize=35)
ax.set_title('4RIGHT-ACCIDENT', fontsize=40)
plt.xlabel('AMP', fontsize=35, color='black')
plt.ylabel('COUNTS', fontsize=35, color='black')
ax.loglog(x, y, yerr=yerr, linewidth=5)
plt.show()

Solution

  • I adjusted your code a bit, so it does not read you local files but it plots the simulated data (np.arange):

    from matplotlib import pyplot as plt
    import numpy as np
    
    x = np.arange(182)
    y = np.arange(182)
    yerr = np.arange(182).astype("float64") * 0.1
    
    fig, ax = plt.subplots(figsize=(8, 6))
    ax.tick_params(axis='both', labelsize=35)
    ax.set_title('4RIGHT-ACCIDENT', fontsize=40)
    plt.xlabel('AMP', fontsize=35, color='black')
    plt.ylabel('COUNTS', fontsize=35, color='black')
    ax.errorbar(x, y, yerr)
    # set the x and y scale manually:
    ax.set_xscale('log')
    ax.set_yscale('log')
    plt.show()
    

    Which is the same plot (but with error bars) compared to:

    fig, ax = plt.subplots(figsize=(8, 6))
    ax.tick_params(axis='both', labelsize=35)
    ax.set_title('4RIGHT-ACCIDENT', fontsize=40)
    plt.xlabel('AMP', fontsize=35, color='black')
    plt.ylabel('COUNTS', fontsize=35, color='black')
    ax.loglog(x, y)