Olgak
Olgak

Reputation: 11

How to plot multiple data sets from excel file in one plot in matplotlib?

I would like to learn how to plot multiple data sets taken from excel in one plot. The code below (provided kindly by another user) plots data sets in separate plots. It works great. Now I need to combine data for other purposes to show in one plot.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import openpyxl as xl
df = pd.read_excel("C:\\temp\\test.xlsx", sheet_name="Sheet2", skiprows=5)
print(df.columns)
def grouped(iterable, n):
    return zip(*[iter(iterable)]*n)
pair_count = len(list(grouped(df.columns,2)))
pair = 1
plt.figure(figsize=(10,5))
for x_col,y_col in grouped(df.columns,2):
  x=np.array(df[x_col].values)
  y=np.array(df[y_col].values)
  plt.subplot(1,pair_count,pair)
  plt.xlim(0.1,15)
  plt.ylim(300,800)
  plt.plot(x,y)
  plt.title(f"{pair}. th plot")
  plt.xlabel(f"{x_col}")
  plt.ylabel(f"{y_col}")
  pair += 1
plt.show()

It should look like this: enter image description here I would really appreciate your help!

Tried adding fig, ax = plt.subplots() but it created 10 separate graphs.

Upvotes: 0

Views: 126

Answers (1)

Ze'ev Ben-Tsvi
Ze'ev Ben-Tsvi

Reputation: 1432

plot method is enough to add a new line:

def col_pairs(columns):
    return [(columns[i], columns[j]) for i, j in zip(range(0, len(columns), 2), range(1, len(columns), 2))]

for col_x, col_y in col_pairs(df.columns):
    plt.plot(df[col_x], df[col_y], label=f"Line {col_x} vs {col_y}", marker='o')

plt.legend()
plt.show()

output:

enter image description here

Upvotes: 1

Related Questions