I'm trying to pass a function that plots various objects for each unique label. Using the df below, A-D
are used to plot various objects. I then pass each unique value in label
to the function.
I'm hoping to pass something more efficient that calling the function on each unique item in a list. Iterating through the list to produce a separate figure for each unique value in label
. Using below, this should be 3 (X,Y,Z)
.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import random
def plot(dfs, label):
fig, ax = plt.subplots()
for l in label:
df = dfs[dfs['label'] == l]
x1 = df['A']
y1 = df['B']
x2 = df['C']
y2 = df['D']
plt.scatter(x1, y1, c = 'orange', marker = 'o', zorder = 3)
plt.scatter(x2, y2, c = 'green', marker = 'o', zorder = 2)
ax.plot([x1,x2],[y1,y2], color = 'k', linestyle = '-', linewidth = 1)
plt.show()
np.random.seed(2020)
df = pd.DataFrame(np.random.randint(0,20,size=(20, 4)), columns=list('ABCD'))
labels = df['A'].apply(lambda x: random.choice(['X', 'Y', 'Z']) )
df['label'] = labels
unq_label = df['label'].unique()
figs = df.groupby('label').apply(plot,unq_label)
from Plot lines for unique label in col - Python
No comments:
Post a Comment