Black Lives Matter. Please consider donating to Black Girls Code today.
Learn how to use COVID-19 data in open source Dash apps. Register for the Sept 23rd webinar with IQT!

Problem with my first plotly python graph

I am following the example here: http://moderndata.plot.ly/update-plotly-charts-with-cron-jobs-and-python/ to set up a line graph that tracks the weather temperatures in Montreal and San Francisco and gets updated through a cron job. I am able to run the python script every 15 minutes via a Windows Scheduled Task, but for some reason sometimes the values get flip-flopped (the value is supposed to be for Montreal but instead it’s marked as being for San Francisco). The code looks the same as in the example. Why is this happening?

Could you provide a code snippet?

sf_lookup_url = 'http://api.wunderground.com/api/' + api_key + '/geolookup/conditions/q/CA/San_Francisco.json'
mtl_lookup_url = 'http://api.wunderground.com/api/' + api_key + '/conditions/q/Canada/Montreal.json'

urls = { 'MTL': mtl_lookup_url, 'SF': sf_lookup_url }
temps = { 'MTL': [], 'SF': [] }

for city in temps.keys():

  #f = urllib2.urlopen(urls[city])
  f = urllib.request.urlopen(urls[city])

  json_string = f.read().decode('utf8')
  parsed_json = json.loads(json_string)

  temps[city].append( parsed_json['current_observation']['temp_c'] )
  temps[city].append( parsed_json['current_observation']['temp_f'] )
  # print "Current temperature in %s is: %s C, %s F" % (city, temps[city][0], temps[city][1] )
  f.close()

layout = Layout(
  title='Current temperature in Montreal and San Francisco',
  titlefont=Font(
    family='"Open sans", verdana, arial, sans-serif',
    size=17,
    color='#444'
  ),
  font=Font(
    family='"Open sans", verdana, arial, sans-serif',
    size=12,
    color='#444'
  ),
  showlegend=True,
  autosize=True,
  width=803,
  height=566,
  xaxis=XAxis(
    title='Click to enter X axis title',
    titlefont=Font(
      family='"Open sans", verdana, arial, sans-serif',
      size=14,
      color='#444'
    ),
    range=[1418632334984.89, 1418632334986.89],
    domain=[0, 1],
    type='date',
    rangemode='normal',
    autorange=True,
    showgrid=False,
    zeroline=False,
    showline=True,
    autotick=True,
    nticks=0,
    ticks='inside',
    showticklabels=True,
    tick0=0,
    dtick=1,
    ticklen=5,
    tickwidth=1,
    tickcolor='#444',
    tickangle='auto',
    tickfont=Font(
      family='"Open sans", verdana, arial, sans-serif',
      size=12,
      color='#444'
    ),
    mirror='allticks',
    linecolor='rgb(34,34,34)',
    linewidth=1,
    anchor='y',
    side='bottom'
  ),
  yaxis=YAxis(
    title='Temperature (degrees)',
    titlefont=Font(
      family='"Open sans", verdana, arial, sans-serif',
      size=14,
      color='#444'
    ),
    range=[-5.968375815056313, 57.068375815056314],
    domain=[0, 1],
    type='linear',
    rangemode='normal',
    autorange=True,
    showgrid=False,
    zeroline=False,
    showline=True,
    autotick=True,
    nticks=0,
    ticks='inside',
    showticklabels=True,
    tick0=0,
    dtick=1,
    ticklen=5,
    tickwidth=1,
    tickcolor='#444',
    tickangle='auto',
    tickfont=Font(
      family='"Open sans", verdana, arial, sans-serif',
      size=12,
      color='#444'
    ),
    exponentformat='B',
    showexponent='all',
    mirror='allticks',
    linecolor='rgb(34,34,34)',
    linewidth=1,
    anchor='x',
    side='left'
  ),
  legend=Legend(
    x=1,
    y=1.02,
    traceorder='normal',
    font=Font(
      family='"Open sans", verdana, arial, sans-serif',
      size=12,
      color='#444'
    ),
    bgcolor='rgba(255, 255, 255, 0.5)',
    bordercolor='#444',
    borderwidth=0,
    xanchor='left',
    yanchor='auto'
  )
)

cur_time = datetime.datetime.now() # current date and time
data=[]
temp_types = ['C','F']
for city in temps.keys():
  for i in range(len(temp_types)):
    data.append(\
      Scatter( x=[cur_time], y=[temps[city][i]], \
      line=Line(dash='dot') if i==0 else Line(),
      mode='lines+markers', \
      name='{0} ({1})'.format(city,temp_types[i]) ) )

data = Data( data )
fig = Figure(data=data, layout=layout)
plot_url=py.plot(fig, filename='montreal-and-san-francisco-temperatures',fileopt='extend',auto_open=False)

This may be because of the way dict is used in this example. Since dict is unordered, when the end of the code snippet uses for city in temps.keys(), I think the data is being appended in different orders. Can you try the following?

  1. Import OrderedDict --> from collections import OrderedDict
  2. Use an OrderedDict instead of a normal dict by changing
    temps = { 'MTL': [], 'SF': [] }
    to
    temps = OrderedDict([('MTL', []), ('SF', [])])

Note that you can always create a dictionary from an iterable (in this case a list). Here, we use this ordered iterable so that there are no surprises when we create the temps variable.

Let us know if this fixes the issue you’re seeing and we can update the example accordingly.