Search code examples
pythonpandasmatplotlibquandl

Multiple graphs in a single plot with a for loop


I am trying to display in a single plot n graphs, n being the number of U.S states number.

The compiler doesn't like those 2 linesx[j] = df['Date'] y[j] = df['Value']

=> TypeError: 'NoneType' object is not subscriptable

import quandl
import pandas as pd
import matplotlib.pyplot as plt

states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')
j = 0
x = []
y = []

for i in states[0][0][1:]:
        df = quandl.get("FMAC/HPI_"+i, authtoken="yourtoken" )
        df = df.reset_index(inplace=True, drop=False)
        x[j] = df['Date']
        y[j] = df['Value']
        j += 1

plt.plot(x[j],y[j])
plt.xlabel('Date')
plt.ylabel('Value')
plt.title('House prices')
plt.legend()
plt.show()

Solution

  • Your problem with this particular error is that you are using the inplace argument and assigning back to variable df. When using inplace argument equals to True, the return is None.

    print(type(df.reset_index(inplace=True, drop=False)))
    NoneType
    
    print(type(df.reset_index(drop=False)))
    pandas.core.frame.DataFrame
    

    Use either inplace=True and don't assign back to df:

    df.reset_index(inplace=True, drop=False)
    

    or use default for inplace=False and assign back to variable df

    df = df.reset_index(drop=False)
    

    There are some other logic errors here.

    EDIT to get a working chart (limit to 20 for testing)

    for i in states[0][0][1:20]:
            df = quandl.get("FMAC/HPI_"+i, authtoken="yourtoken" )
            df.reset_index(inplace=True, drop=False)
            plt.plot('Date','Value',data=df)
    
    
    # plt.plot(x[j],y[j])
    plt.xlabel('Date')
    plt.ylabel('Value')
    plt.title('House prices')
    plt.show()
    

    enter image description here