Reputation: 1195
I have a JSON array of around 3000 records each spaced 1 minute apart which I want to plot on a timeseries graph using matplotlib
. However I cannot get the data to display properly on a chart with the date and times along the x axis.
The records are formatted as follows:
{
"datetime": "10-07-2017 21:57:37",
"deviceid": "PiJCLabDoor",
"dht11": 24.0,
"dht22": null,
"id": 39751,
"motion": 0.0,
"pressure": null,
"uv": 0.04,
"voc": 126.0
}
I have the following code
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
data = pd.read_json('PiJCLabDoor.json', convert_dates=['datetime'])
dataframe = DataFrame(data)
for i in range(0, dataframe.shape[0] -1):
if (dataframe.loc[i, 'dht11'] - dataframe.loc[i+1, 'dht11']) > 3 :
dataframe.loc[i+1, 'dht11'] = dataframe.loc[i,'dht11']
These lines of code yield the following chart:
plt.figure(figsize=(20,7)
plt.plot(dataframe['datetime'], dataframe['dht11'])
plt.show()
And these lines of code yield the following chart:
plt.rcParams['figure.figsize'] = (20,6)
plt.plot(dataframe['dht11'])
plt.show()
The second chart is what the data should look like however the first chart has dates on the x axis.
How do I get the date and time to appear on the x axis of the second chart? Thanks
Upvotes: 0
Views: 1732
Reputation: 1597
First thing, remember to convert datetime to Pandas datetime (pd.to_datetime()) To make the dates appear on second graph set datetime column as index, something like:
plt.plot(dataframe.set_index('datetime')['dht11'])
EDIT:
So if i get it right you have something like this:
There is a 1 week gap between dates, and you want to have them one next to another so:
x = np.arange(len(a['date']))
plt.plot(x, a['value'])
plt.xticks(x, a['date'], rotation=45)
First I do something like in your first graph, then I change the name of xlabels to have the same as dates. Result looks like that:
But you might find that the xticks appears too often, then just change one line there, like this:
plt.xticks(x[::3], a['date'][::3], rotation=45)
So now only every third date will appear on the graph.
EDIT 2:
If you want to set only X main dates on your x-axis use this:
from matplotlib.ticker import LinearLocator
plt.plot(x, a['value'])
plt.xticks(x, a['date'], rotation=45)
ax = plt.gca()
ax.get_xaxis().set_major_locator(LinearLocator(numticks=5))
In numticks you specify how many ticks should appear
Upvotes: 3