Ann Kriebel
Ann Kriebel

Reputation: 109

How to add x-axis on plot?

I am trying to plot some data, but I don't know how I can add the date values on the x-axis on my graph. Here is my code:

import pandas as pd
import numpy as np

%matplotlib inline
%pylab inline
import matplotlib.pyplot as plt
pylab.rcParams['figure.figsize'] = (15, 9)
df["msft"].plot(grid = True) 

enter image description here

The description of the image is a plot, but the x-axis just has numbers, but I am looking for dates to appear on x-axis. The dates are in the date column in the dataframe.

Here is what the dataframe looks like:

                  date  msft  nok  aapl  ibm  amzn
1  2018-01-01 09:00:00   112    1   143  130  1298
2  2018-01-01 10:00:00   109   10   185  137  1647
3  2018-01-01 11:00:00    98   11   146  105  1331
4  2018-01-01 12:00:00    83    3   214  131  1355

Can you offer some help on what I am missing?

Upvotes: 2

Views: 290

Answers (2)

bobrobbob
bobrobbob

Reputation: 1281

one way to do it is the set_xticklabels function, though Mr. T's answer is the proper way to go

ax = plt.subplot(111)
df["msft"].plot(grid = True)
ax.set_xticklabels(df['date'])
plt.xticks(np.arange(4))

with the data provided:

set_xticklabels

Upvotes: -1

Mr. T
Mr. T

Reputation: 12410

Your column date is just another column for pandas, you have to tell the program that you want to plot against this specific one. One way is to plot against this column:

from matplotlib import pyplot as plt
import pandas as pd
#load dataframe
df = pd.read_csv("test.txt", delim_whitespace=True)
#convert date column to datetime object, if it is not already one
df["date"] = pd.to_datetime(df["date"])

#plot the specified columns vs dates
df.plot(x = "date", y = ["msft", "ibm"], kind = "line", grid = True)
plt.show()

For more pandas plot options, please have a look at the documentation.

Another way would be to set date as the index of the dataframe. Then you can use your approach:

df.set_index("date", inplace = True)
df[["msft", "ibm"]].plot(grid = True) 
plt.show()

The automatic date labels might not be, what you want to display. But there are ways to format the output and you can find examples on SO.

Upvotes: 2

Related Questions