Python Beginer here. I have a .tsv file with data like this:
Date Time Day Sales
2020-08-07 17:20:04 Friday 37
2020-08-07 17:30:05 Friday 38
...and so on
I would like to plot this. I've tried this:
from pandas import read_csv
from matplotlib import pyplot
import datetime
import pandas as pd
series = read_csv('data.tsv', sep="\t")
pyplot.figure()
x = pd.to_datetime(series['Time']).dt.time
y = series['Sales']
pyplot.plot(x,y)
pyplot.show()
It works! However, I'd like to show every hour of the day on the x-axis. I've tried doing:
times = [datetime.datetime.strptime(str(i), '%H') for i in range(24)]
pyplot.xticks(times)
... but it doesn't work. Right now it seems quite random whats on the x-axis (00:00, 05:33:20, 11:06 ...)
Any ideas?
Here is some example code. AutoDateFormatter() sets an automatic format. DateFormatter('%H:%M') set hours:minutes as format.
See the docs for more options, both for the locator and for the formatter.
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np
times = pd.date_range(start='2020-02-14 20:30', end='2020-02-14 22:20', freq='7min')
series = pd.DataFrame({'Time': times,
'Sales': 20 + np.random.uniform(-1, 1, len(times)).cumsum()})
x = series['Time']
y = series['Sales']
plt.plot(x, y)
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
# plt.gca().xaxis.set_major_formatter(mdates.AutoDateFormatter())
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
plt.show()
Related
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader as web
#This makes a chart w/3 hour intervals and I would need something like 30 minutes
style.use("ggplot")
start = dt.datetime(2019,4,24)
end = dt.datetime(2019,5,25)
df = web.get_data_yahoo("TSLA", start, end)
df["Adj Close"].plot()
plt.title('Tesla Price v. First Quarter Earnings 2019')
plt.ylabel('USD')
plt.show()
The following example shows how to set the primary scale at 7-day intervals and hide the secondary scale as an example. Other variations can be found on
formatter page and Locator page.
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style
import pandas as pd
import pandas_datareader as web
fig, ax = plt.subplots()
#This makes a chart w/3 hour intervals and I would need something like 30 minutes
style.use("ggplot")
start = dt.datetime(2019,4,24)
end = dt.datetime(2019,5,25)
df = web.get_data_yahoo("TSLA", start, end)
ax = df["Adj Close"].plot()
days = mdates.DayLocator(interval=7)
days_fmt = mdates.DateFormatter('%m/%d')
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(days_fmt)
ax.minorticks_off()
plt.title('Tesla Price v. First Quarter Earnings 2019')
plt.ylabel('USD')
plt.show()
Hi I am trying to plot(matplotlib) live data from a DHT11 Temp sensor to a graph.
x = current time
y = temperature
I import datetime as dt
then use
xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
But I keep on getting
"//ValueError: could not convert string to float: '22:20:02.817201'//"
I don't know what else to try.
thx
Lappies
import datetime as dt
import numpy as np
now=dt.datetime.now()
delta=dt.timedelta(seconds=5)
times=[now+delta*i for i in range(10)]
temps=np.arange(10)**2
import matplotlib.pyplot as plt
fig,ax=plt.subplots()
ax.plot(times,temps)
fig.show()
If you want to play with the formatting of the time axis, use import matplotlib.dates as mdates and something like ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S\n%b-%d'))
I have a series whose index is datetime that I wish to plot. I want to plot the values of the series on the y axis and the index of the series on the x axis. The Series looks as follows:
2014-01-01 7
2014-02-01 8
2014-03-01 9
2014-04-01 8
...
I generate a graph using plt.plot(series.index, series.values). But the graph looks like:
The problem is that I would like to have only year and month (yyyy-mm or 2016 March). However, the graph contains hours, minutes and seconds. How can I remove them so that I get my desired formatting?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# sample data
N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
np.random.seed(365) # for a reproducible example of values
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)
fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)
# use formatters to specify major and minor ticks
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_ = plt.xticks(rotation=90)
You can try something like this:
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
fig,ax1 = plt.subplots()
plt.plot(df.index,df.values)
monthyearFmt = mdates.DateFormatter('%Y %B')
ax1.xaxis.set_major_formatter(monthyearFmt)
_ = plt.xticks(rotation=90)
You should check out this native function of matplotlib:
fig.autofmt_xdate()
See examples on the source website Custom tick formatter
I am trying to plot some data from pandas. First I group by weeks and count for each grouped week, them I want to plot for each date, however when I try to plot I get just some dates, not all of them.
I am using the following code:
my_data = res1.groupby(pd.Grouper(key='d', freq='W-MON')).agg('count').u
p1, = plt.plot(my_data, '.-')
a = plt.xticks(rotation=45)
My result is the following:
I wanted a value in the x-axis for each date in the grouped dataframe.
EDIT: I tried to use plt.xticks(list(my_data.index.astype(str)), rotation=45)
The plot I get is the following:
Please find a working chunk of code below:
from datetime import date, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
a = pd.Series(np.random.randint(10, 99, 10))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(pd.date_range(date(2016,1,1), periods=10, freq='D'), a)
plt.gcf().autofmt_xdate()
Hope it helps :)
I have a dataFrame with datetimeIndex and two columns with int values. I would like to plot on the same graph Col1 as a bar plot, and Col2 as a line plot.
Important feature is to have correctly labeled x-axis as datetime, also when zooming in-out. I think solutions with DateFormatter would not work, since I want a dynamic xtick labeling.
import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt
import numpy as np
startDate = dt.datetime(2018,1,1,0,0)
nrHours = 144
datetimeIndex = [startDate + dt.timedelta(hours=x) for x in range(0,nrHours)]
dF = pd.DataFrame(index=datetimeIndex)
dF['Col1'] = np.random.randint(1,3,nrHours)
dF['Col2'] = np.random.randint(3,6,nrHours)
axes = dF[['Col1']].plot(kind='bar')
dF[['Col2']].plot(ax=axes)
What seemed to be a simple task turns out being very challenging. Actually, after extensive search on the net, I still haven't found any clean solutions.
I have tried to use both pandas plot and matplotlib.
The main issue arises from the bar plot that seems to have difficulties handling datetime index (prefers integers, in some cases it plot dates but in Epoch 1970-1-1 style which is equivalent to 0).
I finally found a way using mdates and date2num. The solution is not very clean but provides an efficient solution to:
Combine bar and line plot on same graph
Using datetime on x-axis
Correctly and dynamically displaying x-ticks time labels (also when zooming in and out)
Working example :
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import datetime as dt
import numpy as np
startDate = dt.datetime(2018,1,1,0,0)
nrHours = 144
datetimeIndex = [startDate + dt.timedelta(hours=x) for x in range(0, nrHours)]
dF = pd.DataFrame(index=datetimeIndex)
dF['Col1'] = np.random.randint(1,3,nrHours)
dF['Col2'] = np.random.randint(3,6,nrHours)
fig,axes = plt.subplots()
axes.xaxis_date()
axes.plot(mdates.date2num(list(dF.index)),dF['Col2'])
axes.bar(mdates.date2num(list(dF.index)),dF['Col1'],align='center',width=0.02)
fig.autofmt_xdate()
Sample output: