Search code examples
numpymatplotlibx-axis

Feeding pyplot with different size arrays on x and y values


I have two numpy arrays. One is for x axis entries, the other is for y axis as you can see in the code below

    plt.figure(figsize=(10, 10))
    plt.plot(range(0,len(TVals_R)),TVals,'bo',markersize=1,label='Dry Run') #I need x and y arrays in different size here
    plt.figure(figsize=(10, 10))
    plt.ylabel('Temperature ($^\circ$C)')
    plt.xlabel('Measurement')
    plt.title("Temperature vs. Measurement")
    plt.legend(loc="upper right")

On the x axis, I want to use a bigger number than y array such as len(TVals_R). since I will add two more lines to the graph with different x axis ranges. But it returns the error ValueError: x and y must have same first dimension, but have shapes (920,) and (498,)

Is there a way to use different size lists on pylot?

I also tried using different axes for adding two different sized lines in the graph, but since I have a third one coming, I can't use it. Here what I tried

    plt.figure(figsize=(10, 10))
    fig,ax1=plt.subplots()
    ax2=ax1.twiny()
    ax3=ax1.twiny()
    curve1, = ax1.plot(range(0,len(TVals)),TVals,'bo',markersize=1,label='Dry Run')
    curve2, = ax2.plot(range(0,len(TVals_R)),TVals_R,'ro',markersize=1,label='Radiation Run')
    curve3, = ax3.plot(range(0,len(TVals)),TVals_interpolated_R,'go',markersize=1,label='handheld meter and \n linear interpolation')
    curves = [curve1,curve2,curve3]
    ax2.legend(curves, [curve.get_label() for curve in curves]) 
    ax1.set_xlabel('Measurement', color=curve1.get_color()) 
    ax2.set_xlabel('Measurement', color=curve2.get_color())
    ax1.set_ylabel('Temperature ($^\circ$C)')  
    plt.ylabel('Temperature ($^\circ$C)')
    #plt.xlabel('Measurement')
    plt.title("Temperature vs. Measurement")

which returns the error ValueError: x and y must have same first dimension, but have shapes (920,) and (498,)

Instead of separating axes into ax1,ax2 etc, I also tried adding empty elements to smaller lists to match the biggest list, but appending [] in numpy adds 0 (zero) which is misleading in my data

I appreciate any help on either approaches.


Solution

  • It looks like the best way of doing this is to ignore errors and so 2 plots with different x-axis ranges can be overlaid. And this solutions doesn't require fig, ax separation.

        plt.figure(figsize=(10, 10))
        try:
            plt.plot(range(0,len(TVals)),TVals,'o',markersize=1,label='Dry Run')
            plt.plot(range(0,len(TVals_R)),TVals_R,'ro',markersize=1,label='Radiation Run')
            plt.plot(range(0,len(TVals)),TVals_interpolated,'go',markersize=1,label='handheld meter and \n linear interpolation')
        except ValueError:
                pass
        plt.ylabel('Temperature ($^\circ$C)')
        plt.xlabel('Measurement')
        plt.title("Temperature vs. Measurement")
        plt.legend(loc="upper right")
        plt.show()