如何使用Python制作具有两个y轴(x、y1和y2)的散点图

2024-09-29 17:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个散点图,在上面我可以有两个“y”轴(y1轴=产量(Kg/ha),在右边;y2轴=面积(公顷),在左边),在年份“x”轴上。并显示“趋势线”。 提前谢谢

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

Tags: cropsfalseaxpdx1x2legendha
2条回答
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()

熊猫散点图:https://pandas.pydata.org/pandas-docs/version/1.3/reference/api/pandas.DataFrame.plot.scatter.html

趋势线:How to add trendline in python matplotlib dot (scatter) graphs?

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

相关问题 更多 >

    热门问题