1

For the following

from datetime import datetime
import pandas as pd
from pandas import Timestamp
import matplotlib
import matplotlib.pylab as plt
import matplotlib.dates as mdates
#%matplotlib inline 
sorted(df.columns)
df = df[df.region=="US"]
df.set_index('date')
df.head(50)
def plot_cat(df_input, cat, color="green"):
    axis = df_input[cat].plot(figsize=(10,6), color=color, fontsize=10, zorder=2)
    axis.set_xlabel("date", fontsize=font_size)
    axis.set_ylabel("", fontsize=font_size); 
    axis.axhline(y=0)
plot_cat(df, "retail", "red") 

Using the following data https://pastebin.pl/view/b7f35915

The resulting graph does not use "date" for the x-axis.

Though I set index to be date it does not appear to do this. The output from df.head(50) above is as such:

    region  date    retail
0   US  2020-02-15  5.0
1   US  2020-02-16  8.0
2   US  2020-02-17  5.0
3   US  2020-02-18  0.0
4   US  2020-02-19  3.0
5   US  2020-02-20  1.0
6   US  2020-02-21  3.0
7   US  2020-02-22  9.0
8   US  2020-02-23  6.0
9   US  2020-02-24  3.0
10  US  2020-02-25  4.0
11  US  2020-02-26  8.0
12  US  2020-02-27  9.0
13  US  2020-02-28  10.0
14  US  2020-02-29  12.0

I am not sure why this isn't being set as the index, and I believe this to be the reason why the matplot graph fails to have the correct x-axis.

There are no warning messages or errors at any stage.

2 Answers 2

1

@gtomer's answer should solve your problem. Another option without changing your data is pass x to plot:

def plot_cat(df_input, cat, color="green"):
    # change here
    axis = df_input.plot(x='date', y=cat,
                         figsize=(10,6), color=color, 
                         fontsize=10, zorder=2)

    axis.set_xlabel("date", fontsize=font_size)
    axis.set_ylabel("", fontsize=font_size); 
    axis.axhline(y=0)

plot_cat(df, 'retail', 'red')

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Okay when I do that nothing seems to change. Unfortunately when I change the code to df = df.set_index('date') I get the error message "float() argument must be a string or a number, not 'Period'"
Please check your code a gain. I updated the answer with output of my code with sample data.
1

Change the set_index row to:

df = df.set_index('date')

or:

df.set_index('date', inplace=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.