First, import a few modules from the Plotly python package:
import plotly.plotly as py
import plotly.tools as tls
from plotly.graph_objs import *
trace1 = Scatter(
x = ['07/11-07:59:40', '07/11-07:59:42', '07/11-07:59:50', '07/11-08:00:00'],
y = ['10','20','5','15']
)
trace2 = Scatter(
x = ['07/11-07:59:40', '07/11-07:59:43', '07/11-07:59:51', '07/11-08:00:00'],
y = ['1','10','5','10']
)
data = Data([trace1, trace2])
fig = Figure(data= data)
py.iplot(fig, filename='netflix_datetimes1')
Here, the x-coordinates are taken as strings.
As with all string coordinates send to Plotly, each unique x element correspond to a coordinate point. The inferred coordinates are created in sequence, from the first element to last element and from the first trace to the last.
In other words, Plotly cannot infer that '07/11-07:59:43'
is in fact smaller than '07/11-07:59:50'
.
Plotly understands Python datetimes (built with the datetime
package of the Standard Library). More info on Python datetime can be found here.
So,
from datetime import datetime
def convert_to_datetime(times):
return [datetime.strptime(time+' 2014', '%m/%d-%X %Y') for time in times]
# Note that we must the year to each datetime in order to fully define them
trace1 = Scatter(
x = convert_to_datetime(['07/11-07:59:40',
'07/11-07:59:42',
'07/11-07:59:50',
'07/11-08:00:00']),
y = ['10','20','5','15']
)
trace2 = Scatter(
x = convert_to_datetime(['07/11-07:59:40',
'07/11-07:59:43',
'07/11-07:59:51',
'07/11-08:00:00']),
y = ['1','10','5','10']
)
data = Data([trace1, trace2])
fig = Figure(data= data)
py.iplot(fig, filename='netflix_datetimes2')
Plotly also understands a specific string format.
If you have the chance to modify the string format, this solution does not require the datetime
package:
trace1 = Scatter(
x = ['2014-07-11 07:59:40',
'2014-07-11 07:59:42',
'2014-07-11 07:59:50',
'2014-07/11 08:00:00'],
y = ['10','20','5','15']
)
trace2 = Scatter(
x = ['2014-07-11 07:59:40',
'2014-07-11 07:59:43',
'2014-07-11 07:59:51',
'2014-07-11 08:00:00'],
y = ['1','10','5','10']
)
data = Data([trace1, trace2])
fig = Figure(data= data)
py.iplot(fig, filename='netflix_datetimes3')
Refer to
About Plotly
Big thanks to
from IPython.display import display, HTML
import urllib2
url = 'https://raw.githubusercontent.com/plotly/python-user-guide/master/custom.css'
display(HTML(urllib2.urlopen(url).read()))