SgtSafety
SgtSafety

Reputation: 62

Matplotlib - Changing Xticks to value on the line not a data point

I'm using matplotlib.pyplot (plt) to plot a graph of temperature against time. I am wanting the xticks to be at 12am and 12pm only, matplot auto picks where the xticks go.

How can I pick exactly 12am and 12pm for each date as the data I'm using doesn't have those data points? Basically I'm wanting an xtick on a point between two data points / on the line between two data points.

Below is a snippet of my data and my function.

 Temp   UNIX Time                Time
 5.04  1490562000 2017-03-26 22:00:00
 3.21  1490572800 2017-03-27 01:00:00
 2.15  1490583600 2017-03-27 04:00:00
 1.66  1490594400 2017-03-27 07:00:00
 6.92  1490605200 2017-03-27 10:00:00
11.73  1490616000 2017-03-27 13:00:00
13.77  1490626800 2017-03-27 16:00:00

def ploting_graph(self):
    ax=plt.gca()
    xfmt = md.DateFormatter('%d/%m/%y %p')
    ax.xaxis.set_major_formatter(locator)
    plt.plot(self.df['Time'],self.df['Temp'], 'k--^')
    plt.xticks(rotation=10)
    plt.grid(axis='both',color='r')
    plt.ylabel("Temp (DegC)")
    plt.xlim(min(self.df['Time']),max(self.df['Time']))
    plt.ylim(min(self.df['Temp'])-1,max(self.df['Temp'])+1)
    plt.title("Forecast Temperature {}".format(self.location))
    plt.savefig('{}_day_forecast_{}.png'.format(self.num_of_days,self.location),dpi=300)

As hopefully you can see I'm looking for an xtick on the 2017-03-27 00:00:00 and 12:00:00.

Any help would be greatly appreciated and even a push in the right direction would be fantastic! Thank you very much in advanced!

John.

Upvotes: 1

Views: 876

Answers (2)

Try playing with the xticks function on plot. Below is a quick example I tried.

import matplotlib.pyplot as plt
x = [2,3,4,5,6,14,16,18,24,22,20]
y = [1, 4, 9, 6,5,6,7,8,9,5,7]
labels = ['12Am', '12Pm']
plt.plot(x, y, 'ro')
'12,24 are location on x-axis for labels'
plt.xticks((12,24),('12Am', '12Pm'))
plt.margins(0.2)
plt.show()

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339350

You need a locator and a formatter. The locator determines that you only want ticks every 12 hour while the formatter determines how the datetime should look like.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates

dates = ["2017-03-26 22:00:00","2017-03-27 01:00:00","2017-03-27 04:00:00","2017-03-27 07:00:00",
         "2017-03-27 10:00:00","2017-03-27 13:00:00","2017-03-27 16:00:00"]
temps = [5.04, 3.21, 2.15,1.66, 6.92, 11.73, 13.77 ]

df = pd.DataFrame({"Time":dates, "Temp":temps})
df["Time"] = pd.to_datetime(df["Time"], format="%Y-%m-%d %H:%M:%S")


fig, ax = plt.subplots()

xfmt = matplotlib.dates.DateFormatter('%d/%m/%y 12%p')
ax.xaxis.set_major_formatter(xfmt)

locator = matplotlib.dates.HourLocator(byhour=[0,12])
ax.xaxis.set_major_locator(locator)
plt.plot(df['Time'],df['Temp'], 'k--^')
plt.xticks(rotation=10)
plt.grid(axis='both',color='r')
plt.ylabel("Temp (DegC)")
plt.xlim(min(df['Time']),max(df['Time']))
plt.ylim(min(df['Temp'])-1,max(df['Temp'])+1)
plt.title("Forecast Temperature")

plt.show()

enter image description here

Upvotes: 1

Related Questions