Issue
I am trying to create 6 graphs of subplots. 2 of the line plots are on the same row and the row below it will have the Cumulative Plot which will occupy the space of 2 columns. It will do this for col1
and col2
creating 6 plots in total (3 for each range). However the plots overlap how would I be able to fix it and make it so that it fits the format mentioned at Format of the Plots
.
Format of the Plots:
-line plot `col1`(column=1, row=1), line plot `col1` (column=2, row=1)
-cumulative plot `col1`(column= 1 and 2, row=2)
-line plot `col2`(column=1, row=3), line plot `col2` (column=2, row=3)
-cumulative plot `col2`(column= 1 and 2, row=4)
code:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({
'x': [1,2,3,4,5,6],
'col1': [5,3,4,8,9,11],
'col2': [2,6,3,11,3,6]
})
def Graphing():
# Size of the figure
fig = plt.figure(figsize=(16, 9))
for count, (y,plots,iterator,title) in enumerate(zip(
[df['col1'],df['col2']], # Range Columns
[[(4, 2, 1), (4, 2, 2), (4, 1, 2)], [(4, 2, 1), (4, 2, 2), (4, 1, 4)]], #Columns
[0,3], #iterator used to give different names to subplot_
['Column 1', 'Column 2'])): #Column used
for subplot_,add_plot,y,title2 in zip(
[f'sub{iterator+0}',f'sub{iterator+1}',f'sub{iterator+2}'], #Name of the subplot sub0, sub1..
[plots[0],plots[1],plots[2]], # cordinates of the subplot 4, 2, 1), (4, 2, 2) ...
[y,y,np.cumsum(y)],
['Line Plot','Line Plot', 'Cumulative Plot']): # Range values for the plot
#Adds Subplot
subplot_ = fig.add_subplot(*add_plot)
#Title
subplot_.set(title=f'{title} {title2}')
# Sets up the x,y, color of the plot
getattr(subplot_, 'plot')(df['x'],y,color='r', marker='o')
# Show Graph
plt.show()
Graphing()
Output:
Solution
move this inside the first for loop
fig = plt.figure(figsize=(16, 9))
second, show the plot once your inner loop completes
plt.show()
third, modify the sub-plot indexes
[[(4, 2, 1), (4, 2, 2), (4, 1, 3)], [(4, 2, 1), (4, 2, 2), (4, 1, 3)]], #Columns
here is a revised Graphing function
def Graphing():
# Size of the figure
for count, (y,plots,iterator,title) in enumerate(zip(
[df['col1'],df['col2']], # Range Columns
[[(4, 2, 1), (4, 2, 2), (4, 1, 3)], [(4, 2, 1), (4, 2, 2), (4, 1, 3)]], #Columns
[0,3], #iterator used to give different names to subplot_
['Column 1', 'Column 2'])): #Column used
fig = plt.figure(figsize=(16, 9))
for subplot_,add_plot,y,title2 in zip(
[f'sub{iterator+0}',f'sub{iterator+1}',f'sub{iterator+2}'], #Name of the subplot sub0, sub1..
[plots[0],plots[1],plots[2]], # cordinates of the subplot 4, 2, 1), (4, 2, 2) ...
[y,y,np.cumsum(y)],
['Line Plot','Line Plot', 'Cumulative Plot']): # Range values for the plot
#Adds Subplot
subplot_ = fig.add_subplot(*add_plot)
#Title
subplot_.set(title=f'{title} {title2}')
# Sets up the x,y, color of the plot
getattr(subplot_, 'plot')(df['x'],y,color='r', marker='o')
plt.show()
# Show Graph
# plt.show()
Answered By - Naveed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.