3

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")

2 Answers2

2
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()
pyaj
  • 545
  • 5
  • 15
1
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({
    "X": [1, 2 ,3, 4],
    "Y": [2, 4, 9, 7],
    "description": ["a", "b", "c", "d"]})

df.plot.scatter(x="X", y="Y")
z = np.polyfit(df["X"], df["Y"], deg=1)
p = np.poly1d(z)
plt.plot(df["X"], p(df["X"]), "r--")

plt.show()

Pandas scatter plot: https://pandas.pydata.org/pandas-docs/version/1.3/reference/api/pandas.DataFrame.plot.scatter.html

Trendline: How to add trendline in python matplotlib dot (scatter) graphs?

Tzane
  • 2,752
  • 1
  • 10
  • 21