1

I am working on a time series figure where the date progression is on the x axis and the corresponding value for that date is on the y axis.

My code:

from dateutil.parser import parse
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

plt.rcParams.update({'figure.figsize': (10, 7), 'figure.dpi': 120})

# Import as Dataframe
df = pd.DataFrame({'date': ['2021-01-03', '2021-01-05', '2021-01-07', '2021-01-09'],
        'value': ['3', '1', '2', '10']})

# Draw Plot
def plot_df(df, x, y, title="", xlabel='Days', ylabel='Tweets per day', dpi=100):
    plt.figure(figsize=(16,5), dpi=dpi)
    plt.plot(x, y, color='tab:blue')
    plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
    plt.show()

plot_df(df, x=df.index, y=df.value, title='Title')
  • 1
    Does this answer your question? [How to convert string to datetime format in pandas python?](https://stackoverflow.com/questions/32204631/how-to-convert-string-to-datetime-format-in-pandas-python) – Mr. T Jan 10 '21 at 02:30

1 Answers1

1

I made two changes below, the first is converting to datetime object:

df['date'] = pd.to_datetime(df['date'])

the second is change the x variable to the correct date column instead of the index in the plot call

plot_df(df, x=df['date'], y=df.value, title='Title')

full code is below for reference

    # Import as Dataframe
df = pd.DataFrame({'date': ['2021-01-03', '2021-01-05', '2021-01-07', '2021-01-09'],
        'value': [3, 1, 2, 10]})
df['date'] = pd.to_datetime(df['date'])
# Draw Plot
def plot_df(df, x, y, title="", xlabel='Days', ylabel='Tweets per day', dpi=100):
    plt.figure(figsize=(16,5), dpi=dpi)
    plt.plot(x, y, color='tab:blue')
    plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
    plt.show()

plot_df(df, x=df['date'], y=df.value, title='Title')
MaxYarmolinsky
  • 1,117
  • 1
  • 10
  • 16