Search code examples
pythonscatter

How to make a scatter plot with two y axes (x, y1 and y2) with Python


I want to make a scatter plot graph on which I can have two axes of 'y' (axis of y1 = yield (Kg / ha) on the right; axis of y2 = area (hectare) on the left) and have on the year 'x' axis. and show the 'Trendline'. thanks in advance.

crops1 = pd.DataFrame({"x1": crops['Years'],
               "y1_1": crops['Area_ha'], 
               "y1_2": crops['Yield_kg']})

crops2 = pd.DataFrame({"x2": crops['Years'],
               "y2_1": crops['Area_ha'], 
               "y2_2": crops['Yield_kg']})
#plt.scatter(x,y)

fig, ax1 = plt.scatter(x1,y1)
ax2=ax1.twinx()



crops1.scatter(x="x1", y= ["y1_1"], ax=ax1, legend=False)
crops1.scatter(x="x1", y="y1_2", ax=ax2, legend=False, color="r")
crops2.scatter(x="x2", y="y2_1", ax=ax1, legend=False)
crops2.scatter(x="x2", y="y2_2", ax=ax2, legend=False, color="r")

Solution

  • import matplotlib.pyplot as plt
    
    fig, ax1 = plt.subplots()
    
    ax2 = ax1.twinx()
    ax1.scatter(x, y1, color='g')
    ax2.scatter(x, y2, color='b')
    
    ax1.set_xlabel('X data')
    ax1.set_ylabel('Y1 data', color='g')
    ax2.set_ylabel('Y2 data', color='b')
    
    plt.show()