Issue of graph not having the correct datatype

Tell us what’s happening:
Describe your issue in detail here.

Hello,
for some reason the graph my program returns is the wrong datatype leading to an error in the testing module:

AttributeError: 'NoneType' object has no attribute 'get_texts'

I solved the issue for very similar problems in the test module by just doing fig = fig.fig.
For some reason the legend is however diffrent from the X/Y label.
Additionally the scale on my boxplot is of. How can I fix that? (like is there away I can tell pyplot to use a fixed y scale?)

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# Import data (Make sure to parse dates. Consider setting index column to 'date'.)
df = pd.read_csv("fcc-forum-pageviews.csv")
df['date'] = pd.to_datetime(df['date'])
df = df.set_index("date")

# Clean data
df = df.loc[((df["value"]>=df["value"].quantile(0.025))&(df["value"]<=df["value"].quantile(0.975)))]


def draw_line_plot():
    # Draw line plot
    fig = plt.figure(figsize= (1,1))
    plt.xticks(df["value"],df.index.values)
    plt.plot(df["value"],"r")
    plt.xlabel("Date")
    plt.ylabel("Page Views")
    plt.title("Daily freeCodeCamp Forum Page Views 5/2016-12/2019")
    # Save image and return fig (don't change this part)
    fig.savefig('line_plot.png')
    return fig

def draw_bar_plot():
    # Copy and modify data for monthly bar plot
    df_bar = df.resample("M").sum()
    df_bar["count"]= df.resample("M").count()
    df_bar = df_bar.reset_index()
    df_bar_extend = pd.DataFrame({"date": ["2016-01-31","2016-02-27","2016-03-30","2016-04-30"], "value": [0,0,0,0],"count": [1,1,1,1]})
    df_bar = pd.concat([df_bar_extend, df_bar], ignore_index=True)
    df_bar['date'] = pd.to_datetime(df_bar['date'])
    df_bar["Years"]= df_bar["date"].dt.year
    df_bar["Months"]= df_bar["date"].dt.month      
    df_bar = df_bar.set_index("date")
    monthnames = ["January","February","March","April","Mai","June","July","August","September","October","November","December"]
    for i in range(1,13):
      df_bar.loc[df_bar["Months"]==i,"Months"] = monthnames[i-1]
    df_bar["Average Page Views"]=df_bar["value"]/df_bar["count"]
    fig = sns.catplot(x="Years", y= "Average Page Views",hue= "Months",data=df_bar,kind = "bar")
    # Draw bar plot
    # Save image and return fig (don't change this part)
    fig=fig.fig
    
    fig.savefig('bar_plot.png')
    return fig

def draw_box_plot():
    # Prepare data for box plots (this part is done!)
    df_box = df.copy()
    df_box = df_box.reset_index()
    df_bar_extend = pd.DataFrame({"date": ["2016-01-31","2016-02-27","2016-03-30","2016-04-30"], "value": [0,0,0,0]})
    df_box = pd.concat([df_bar_extend, df_box], ignore_index=True)
    df_box['date'] = pd.to_datetime(df_box['date'])
    df_box = df_box.set_index("date")
    df_box.reset_index(inplace=True)
    df_box['Year'] = [d.year for d in df_box.date]
    df_box['month'] = [d.strftime('%b') for d in df_box.date]
    # Draw box plots (using Seaborn)
    fig,ax = plt.subplots(1,2,figsize=(15,10))
    ax1 = sns.boxplot(x=df_box["Year"],y=df_box["value"],ax =ax[0])
    ax1.set_ylabel("Page Views")
    ax1.set_title("Year-wise Box Plot (Trend)")
    ax1.set_ylim(0,200000)
    
    
    ax2 = sns.boxplot(x=df_box["month"],y=df_box["value"],ax =ax[1])
    ax2.set_ylabel("Page Views")
    ax2.set_xlabel("Month")
    ax2.set_title('Month-wise Box Plot (Seasonality)')
    ax2.set_ylim(0,200000)
   
    # Save image and return fig (don't change this part)
    fig.savefig('box_plot.png')
    return fig

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30

Challenge: Page View Time Series Visualizer

Link to the challenge:

It’s not just a “wrong” type - but a “NONE” type.
Meaning as far as Python is concerned, there is “nothing”.

Please provide a link to your project so we can see the entire error message and output.
Chances are one of your commands doesn’t actually create a figure, so you return a nonexistent object.

Here the link: boilerplate-page-view-time-series-visualizer - Replit
I think that it is looking for an axis object but there is none as i used seaborn for the plot.
Here the full error:

Traceback (most recent call last):
  File "/home/runner/boilerplate-page-view-time-series-visualizer/test_module.py", line 42, in test_bar_plot_legend_labels
    for label in self.ax.get_legend().get_texts():
AttributeError: 'NoneType' object has no attribute 'get_texts'

I struggled with this same issue. after a few hours trying to study objects returned by seaborn (and still clueless) the following worked for me:

fig = sns.catplot(data=df_bar,
x=‘year’,
y=‘value’,
hue=‘month’,
kind=‘bar’,
hue_order = [‘January’,‘February’,‘March’,‘April’,‘May’,‘June’,‘July’,‘August’,‘September’,‘October’,‘November’,‘December’],legend = False)
plt.legend()

I opted to have seaborn not create a legend and created one manually and everything passed. hope that helps.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.