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'))
Related
I am using matplotlib (Python), I have y values in seconds (like 1000 seconds) and I want to display the ticks of y-axis in HH:MM:SS format. What is the simple solution to do that (with example).
Y is an integer list represents time duration in seconds
Sample code
import matplotlib.pyplot as plt
import numpy as np
y= np.array([1000,2000,4000,1000])
plt.plot(y)
plt.show()
Best regards
You can use the timedelta function from the datetime module.
import numpy as np
from datetime import timedelta
y= np.array([1000,2000,4000,1000])
y_timedelta = [str(timedelta(seconds=int(s))) for s in y]
Result:
['0:16:40', '0:33:20', '1:06:40', '0:16:40']
Thanks a lot Derek, however I have to use yticks and the full code working is as follows:
import numpy as np
from datetime import timedelta
import matplotlib.pyplot as plt
y= np.array([1000,3000,2000,4000])
y_timedelta = [str(timedelta(seconds=int(s))) for s in y]
plt.plot(y)
plt.yticks(y,y_timedelta)
plt.show()
This is output:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
load_file=pd.read_excel(r'E:\CCNC\CCNCCodes\Modulated
output\plot_oriented_ss_data.xlsx',header=0)
load_file.columns
s=load_file.loc[0:49,['Timeseries','ccn_0.1']] s
s1=s
s['Timeseries'] = s['Timeseries'].astype(str)
plt.plot(s1[0:49]['Timeseries'],s1[0:5762]['ccn_0.1'],color='b')
plt.grid()
plt.show()
Please tell me where do I exact need to make the change to avoid the overlapping of time series in x-axis.
Instead of converting your 'Timeseries' to str, you should convert them to datetime using:
s['Timeseries'] = pd.to_datetime(s['Timeseries'])
In following plot date is not showing on x axis what do to show date time stamp
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import pandas_datareader as web
start=datetime.datetime(2014,1,8)
end =datetime.datetime(2019,1,8)
Tesla=web.DataReader('TSLA',"iex",start,end)
Ford=web.DataReader('F',"iex",start,end)
Tesla["open"].plot(label="Tesla",title="opening Price",figsize=(16,8))
plt.legend()
plt.show()
Your dataframe index is created as dtype object or string, let's convert index to DatetimeIndex using pd.to_datetime:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import pandas_datareader as web
start=datetime.datetime(2014,1,8)
end =datetime.datetime(2019,1,8)
Tesla=web.DataReader('TSLA',"iex",start,end)
Ford=web.DataReader('F',"iex",start,end)
#Change Telsa index to datetime dtype
Tesla.index = pd.to_datetime(Tesla.index)
#Let's do Fords too
Ford.index = pd.to_datetime(Ford.index)
Tesla["open"].plot(label="Tesla",title="opening Price",figsize=(16,8))
plt.legend()
plt.show()
Output:
I am trying to plot information against dates. I have a list of dates in the format "01/02/1991".
I converted them by doing the following:
x = parser.parse(date).strftime('%Y%m%d'))
which gives 19910102
Then I tried to use num2date
import matplotlib.dates as dates
new_x = dates.num2date(x)
Plotting:
plt.plot_date(new_x, other_data, fmt="bo", tz=None, xdate=True)
But I get an error. It says "ValueError: year is out of range". Any solutions?
You can do this more simply using plot() instead of plot_date().
First, convert your strings to instances of Python datetime.date:
import datetime as dt
dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here
Then plot:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()
Result:
I have too low reputation to add comment to #bernie response, with response to #user1506145. I have run in to same issue.
The answer to it is an interval parameter which fixes things up
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt
np.random.seed(1)
N = 100
y = np.random.rand(N)
now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()
As #KyssTao has been saying, help(dates.num2date) says that the x has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102 is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).
Use datestr2num instead (see help(dates.datestr2num)):
new_x = dates.datestr2num(date) # where date is '01/02/1991'
Adapting #Jacek Szałęga's answer for the use of a figure fig and corresponding axes object ax:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt
np.random.seed(1)
N = 100
y = np.random.rand(N)
now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(days,y)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=5))
ax.tick_params(axis='x', labelrotation=45)
plt.show()
I am trying to develop a candlestick chart with matplotlib but for some reason, dates are not coming up in the x-axis. After searching in stackoverflow, I understood that the dates need to be converted to float numbers so i converted them as well but still it's not working. New to this python and matplotlib. ANy help would be greatly appreciated.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc
import matplotlib.dates as dts
import matplotlib.ticker as mTicker
from datetime import datetime
my_file=pd.read_csv("C:\\path\\to\\file\\file.csv",sep=",",names=['Date','Open','High','Low','Close','AdjClose','Volume'],skiprows=1)
dateseries=[]
for i in my_file['Date']:
dateseries.append(dts.date2num(datetime.strptime(i,'%Y-%m-%d')))
print(dateseries)
fig,ax1=plt.subplots()
candlestick2_ohlc(ax1,my_file['Open'], my_file['High'],my_file['Low'], my_file['Close'], width=0.7,colorup='#008000', colordown='#FF0000')
plt.show()
Sample data:
Date,Open,High,Low,Close,Volume1,Volume2
2017-05-08,149.029999,153.699997,149.029999,153.009995,153.009995,48752400
2017-05-09,153.869995,154.880005,153.449997,153.990005,153.990005,39130400
2017-05-10,153.630005,153.940002,152.110001,153.259995,153.259995,25805700
In general, you are right about "the dates need to be converted to float numbers". Then to display dates on x-axis, you would need to "convert" them back. If you don't mind using candlestick_ohlc, that might be easier for setting the x-axis for your case here:
import io
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
from matplotlib.dates import date2num, DayLocator, DateFormatter
import pandas as pd
s = """Date,Open,High,Low,Close,Volume1,Volume2
2017-05-08,149.029999,153.699997,149.029999,153.009995,153.009995,48752400
2017-05-09,153.869995,154.880005,153.449997,153.990005,153.990005,39130400
2017-05-10,153.630005,153.940002,152.110001,153.259995,153.259995,25805700"""
my_file = pd.read_table(io.StringIO(s), sep=',', header=0)
my_file['Date'] = date2num(pd.to_datetime(my_file['Date']).tolist())
fig, ax=plt.subplots()
candlestick_ohlc(ax, my_file.as_matrix())
ax.xaxis.set_major_locator(DayLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
plt.show()