I have two dataframes with values from which I plotted a graph using subplot. One graph is a scatter and the other is a line. Now I want to add two independent legends for this chart. I drew one, but it looks like it was just a dataframe converted into a legend. How do I get two independent legends for one graph or one legend where there will be both points and a line?
The code looks like this
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()
This is the actual graph:
It is hard to answer your question precisely without your data. To have two separate legends on the same plot, you can have two y-axes (left and write) sharing the same x-axis. Each y-axis can then be assigned its own legend as below:
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()