0
votes

I am trying to plot a data of stock close price for each day but on the x-axis, i get no labels on xtick instead of year-month format

I tried to take the "Date" and "Close Price" column in a separate dataframe and then tried plotting them.

I have dataframe similar to this

Date        Close Price
2017-05-15  912.20
2017-05-16  894.70
2017-05-17  887.05
2017-05-18  871.35
2017-05-19  852.40
df_sorted.plot(x="Date", y="Close Price", figsize=(8, 5))
plt.title('Trend in last two years')
plt.ylabel('Close Price') # add y-label
plt.xlabel('Date') # add x-label

plt.show()

the output should have xtick in year-month format
3
post few lines of you dataZaraki Kenpachi

3 Answers

1
votes

Just covert it with pandas to_datetime() function

df_sorted['Date'] = pd.to_datetime(df_sorted['Date'])
df_sorted.plot(x="Date", y="Close Price", figsize=(8, 5))
plt.title('Trend in last two years')
plt.ylabel('Close Price') # add y-label
plt.xlabel('Date') # add x-label

plt.show()

enter image description here

1
votes

If you want the ticks to be shown only once per month, try this:

    import matplotlib.dates as mdates

    df_sorted['Date'] = pd.to_datetime(df_sorted['Date'])

    ax = df_sorted.plot(x="Date", y="Close Price", figsize=(8, 5))
    plt.title('Trend in last two years')
    plt.ylabel('Close Price') # add y-label
    plt.xlabel('Date') # add x-label

    months = mdates.MonthLocator()
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))

    plt.show()

enter image description here

0
votes

You need to use the DateFormatter to get your desired output format.Try this

        from matplotlib import dates

        df_sorted.Date = pd.to_datetime(df.Date)

        ax = df_sorted.plot(x="Date", y="Close Price", figsize=(8, 5))
        plt.title('Trend in last two years')
        plt.ylabel('Close Price') # add y-label
        plt.xlabel('Date') # add x-label

        ax.set(xticks=df.Date.values)
        ax.xaxis.set_major_formatter(dates.DateFormatter("%Y-%m-%d"))
        plt.show()