I have a list of dataframe that I want to render a line chart where making subplots for each dataframe. whereas two different dataframes in the list share same column structures. I want to make subplots (line chart) with minimal code possible. To do so, I referenced this post on SO
but didn't get correct subplots. Below is my current approach for one dataframe:
reproducible data:
here is the minimal list of dataframe on gist file which concatenated from list of dataframes. each of dataframe looks like this:
[![enter image description here][3]][3]
my initial approach
import matplotlib.pyplot as plt
df1=list_of_df[1]
fig, ax=plt.subplots(figsize=(14,8))
plt.plot(df1.index, df['2014'], label="2014")
plt.plot(df1.index, df['2015'], label="2015")
plt.plot(df1.index, df['2016'], label="2016")
plt.plot(df1.index,df['2017'], label="2017")
plt.plot(df1.index,df['2018'], label="2018")
plt.plot(df1.index,df['avg'], "--", label="5-Yr-Avg")
plt.show()
my initial output for single dataframe:
here is the output of above attempt:
[![enter image description here][4]][4]
I am trying to loop through this list of dataframe to get subplots so it can be much easier to compare two subplots with different data. I couldn't able to get that. How can I make this happen? any idea? Thanks
if I used SO
post solution
nrow=2
ncol=2
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
for c in range(ncol):
list_of_df[count].plot(ax=axes[r,c])
count=+1
the output of this code is not correct. I am expecting two subplots for two dataframe. How to fix this? I think iterating column was wrong, that's why I got 6 subplots, I should iterate by the index of dataframe. Any idea?
my new attempt:
I am trying to reduce line of codes that implemented in my initial attempt. Since I have list of dataframe, I might code as follow:
fig, ax = plt.subplots(figsize=(10,8))
for x in range(len(df_list)):
ax.plot(df_list[x].index, df_list[x].columns, kind='line')
plt.show()
but this gave me value error as follow:
ValueError: x and y must have same first dimension, but have shapes (12,) and (6,)
why this error raised? Is there any way to generalize my initial implementation to list of dataframe for making subplots? any idea?