0

I am making a figure with subplots. The number of subplots is dynamic and depending on df.shape.

This is working but i am not satisfied. I have 3 Questions:

1) Is it possible to optimize the plot part? if k==b is lil bit annoying

2) How can I delete the last 3 empty subplots?

3) I was thinking of making a static figure (size=4,4) and opening a new one after the figure is full. How can I realize this?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math

import string
import random

# got generator from here: 
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits

def id_generator(size=4, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

#%% make random data
labels = []
for i in range(0,27):
    labels.append(id_generator())

mat = np.random.rand(20,27)
df = pd.DataFrame(mat,columns=labels)

#%% plot
k = 0 #go left
l=0 #go down
b = 5 #static number for columns
a = math.ceil(len(labels)/5) #round up for 'go down'
fig, axs = plt.subplots(
    a,b, figsize=(10, 10),sharex=True, constrained_layout=True
)
for j in labels:
    axs[l,k].plot(df[j])
    k+=1
    if k == b:
        k = 0
        l+=1

Edit: With help of Chris A the 3 Questions above are solved.

I found out how to change the xlabel,xlim and title. Is it possible to change the position of the legend to the top left corner? Cant find anything in the documentation and how can i hand over a list with ylabels?

df.index.name = 'xlabel'
fig = df.plot(subplots=True, title= 'Make title',y=labels,layout=(-1, 5), figsize=(10, 10),grid=True,xlim=[0,20]) #xticks=[0,5,10,15,20]
credenco
  • 255
  • 2
  • 12
  • 1
    You could try `layout` argument of `DataFrame.plot` method. You can pass in `-1` for one of the dimensions and it will work dynamically. eg `df.plot(subplots=True, layout=(-1, 5), figsize=(10, 10))` – Chris Adams Feb 21 '20 at 10:53
  • Wow, thank you. One row for all plots :D But i need also to set the labels ticks and everything. Maybe i will need to use matplotlib to handle the layout. – credenco Feb 21 '20 at 10:59
  • How are you altering ticklabels? – Chris Adams Feb 21 '20 at 11:02
  • 1
    Havent add them in the miniexample. I will check your command and try it :) Thank you – credenco Feb 21 '20 at 11:03

0 Answers0