在一个图中绘制两个独立的图例

Plot two separate legend in one plot

我有两个数据框,其中包含我使用子图绘制图表的值。一张图是散点图,另一张是直线。现在我想为这个图表添加两个独立的图例。我画了一个,但看起来它只是一个转换成图例的数据框。如何为一张图获得两个独立的图例或一个既有点又有线的图例?

代码如下所示

fig = plt.figure()
ax = fig.add_subplot(111)
colors = np.array(["red","green","blue","yellow","pink","black","orange","purple","darkblue","brown","gray","cyan","magenta"])
l1 = ax.scatter(x1,y1, marker='o', label=n1, c=colors, cmap='Dark2')
ax.plot(x2,y2, color="orange")
plt.ylabel('CaO [mmol/l]')
plt.xlabel('OH [mmol/l]')
plt.ylim(0, 14)
plt.xlim(27, 90)
plt.legend()

这是实际图表:

没有你的数据很难准确回答你的问题。要在同一个图上有两个单独的图例,您可以让两个 y 轴(左轴和右轴)共享同一个 x 轴。然后可以为每个 y 轴分配自己的图例,如下所示:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df1 = pd.read_csv(r'C:\Users\Pavol\OneDrive - VŠCHT\Keramika\Článok\Frattini.csv', sep=';')
df2 = pd.read_csv(r'C:\Users\Pavol\OneDrive - VŠCHT\Keramika\Článok\Frattini-norma.csv', sep=';')

x1 = df1.iloc[[0]]
y1 = df1.iloc[[1]]
x2 = df2['OH']
y2 = df2['Standard']

fig = plt.figure(figsize=(12,5))
fig.suptitle("title")
ax1 = fig.add_subplot()
ax2 = ax1.twinx()

colors = np.array(["red","green"])
ax1.scatter(x1,y1, marker='o', c=colors, label = 'legend1', cmap='Dark2')
ax2.plot(df2['OH'], df2['Standard'], label ="legend2")
ax1.set(xlabel='OH [mmol/l]', ylabel= 'CaO [mmol/l]')
plt.ylim(0, 14)
plt.xlim(27, 90)

ax1.legend(loc = 'upper left')
ax2.legend(loc = 'upper right')
plt.show()