コード例 #1
0
def visualize_shares_post(dates,vk,fb,tw, post_id, title):
  locale.setlocale(locale.LC_ALL, 'en_US.utf8')
  api_key      = os.environ.get("PLOTLY_KEY_API")
  py.sign_in('SergeyParamonov', api_key)
  vk_trace = Scatter(
                     x=dates,
                     y=vk,
                     mode='lines+markers',
                     name=u"Вконтакте"
  )
  fb_trace = Scatter(
                     x=dates,
                     y=fb,
                     mode='lines+markers',
                     name=u"Facebook"
  )
  tw_trace = Scatter(
                     x=dates,
                     y=tw,
                     mode='lines+markers',
                     name=u"Twitter"
  )
  data = Data([vk_trace,fb_trace,tw_trace])
  layout = Layout(title=u"Репосты: " + title,
      xaxis= XAxis(title=u"Московское время"), # x-axis title
      yaxis= YAxis(title=u"Репосты"), # y-axis title
      hovermode='closest', # N.B hover -> closest data pt
  )
  plotly_fig = Figure(data=data, layout=layout)
  plotly_filename = "monitor_post_id_" + str(post_id) + "_" + "shares"
  unique_url = py.plot(plotly_fig, filename=plotly_filename)
  return unique_url
コード例 #2
0
ファイル: survData.py プロジェクト: audsc/RWM-Stats
def main():
    try:
        credentials = tls.get_credentials_file()
    except:
        ## except credentials error and print for them to enter something
        credentials = {}
        credentials['username'] = raw_input("Plotly Username: "******"api key: ") ### get password
    py.sign_in(credentials['username'], credentials['api_key'])
    survey_file = "survey.csv"
    run_data = d.main()
    for runner in run_data.runners:
        runner.make_data()
        print runner.median
        #print runner.num , runner.total , runner.count, runner.avg, runner.dur, runner.mpd, runner.rpd
    
    INDEX = completeSurvey()
    #SD is a SurveyData object, has all of the respondents
    SD = read_survey(survey_file, run_data, INDEX)
    mydict = SD.makeDictionary()
    SD.groupSocial()
    SD.groupStarter()
    SD.groupQ1()
    SD.groupQ2()

    #list of runners that did not respond
    nonResponders = sort(run_data, SD)
    #list of runners that did respond
    surveyResponders = SD.responses
    plotQ1(SD)
    #plotQ2(SD)
    #starters(SD)
    plotSocial(SD)
コード例 #3
0
def e20_12_to_15():
    """E20 since Jan2012 to Jun2015"""
    py.sign_in("littlejab", "yblima8sc3")
    chart_min = go.Bar(
        x = ["2012", "2013", "2014", "2015"],
        y = [34.34, 33.79, 34.37, 26.26],
        name = "Min"
    )

    chart_avg = go.Bar(
        x = ["2012", "2013", "2014", "2015"],
        y = [34.35, 33.82, 34.35, 26.26],
        name = "Average"
    )

    chart_max = go.Bar(
        x = ["2012", "2013", "2014", "2015"],
        y = [34.36, 33.87, 34.43, 26.32],
        name = "Max"
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode = "group"
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename = "E20 All Year")
コード例 #4
0
ファイル: main.py プロジェクト: showandtellinar/harbinger
def plot_sentiment(credentials, filename, sentiment, prop):
    access = lambda sen: sen.polarity
    if prop == "subjectivity":
        access = lambda sen: sen.subjectivity

    py.sign_in(credentials[0], credentials[1])

    data = Data(
        [Histogram(
            x=[access(story) for story in x[1]],
            name=x[0],
            histnorm="percent",
            autobinx=False,
            xbins=XBins(
                start=-1.1,
                end=1.1,
                size=0.05,
            )
        )
    for x in sentiment])

    layout = Layout(
        title=prop + " of news sources.",
        barmode='stack'
    )
    fig = Figure(data=data, layout=layout)

    plot_url = py.plot(fig, filename=filename)
    print "Your plot.ly is done at", plot_url
コード例 #5
0
ファイル: e20-2014.py プロジェクト: littlejab/Project-PSIT
def e20_2014():
    """E20 year 2014 price graph"""
    py.sign_in("littlejab", "yblima8sc3")
    chart_min = go.Bar(
        x = ["Jan 14", "Feb 14", "Mar 14", "Apr 14", "May 14", "Jun 14", "Jul 14", "Aug 14", \
            "Sep 14", "Oct 14", "Nov 14", "Dec 14"],
        y = [35.58, 35.58, 35.81, 35.94, 36.07, 35.85, 35.67, 34.94, 33.98, 33.11, 31.67, 28.20],
    name = "Min"
    )

    chart_avg = go.Bar(
        x = ["Jan 14", "Feb 14", "Mar 14", "Apr 14", "May 14", "Jun 14", "Jul 14", "Aug 14", \
            "Sep 14", "Oct 14", "Nov 14", "Dec 14"],
        y = [35.74, 35.22, 35.81, 35.94, 36.07, 35.87, 35.68, 34.94, 33.98, 33.11, 31.67, 28.20],
        name = "Average"
    )

    chart_max = go.Bar(
        x = ["Jan 14", "Feb 14", "Mar 14", "Apr 14", "May 14", "Jun 14", "Jul 14", "Aug 14", \
            "Sep 14", "Oct 14", "Nov 14", "Dec 14"],
        y = [35.76, 35.58, 35.81, 35.94, 36.15, 36.08, 35.81, 34.94, 33.98, 33.11, 31.73, 28.23],
        name = "Max"
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode = "group"
)
コード例 #6
0
def dataPlotlyHandler():

    py.sign_in(username, api_key)

    trace1 = Scatter(
        x=[],
        y=[],
        stream=dict(
            token=stream_token,
            maxpoints=200
        )
    )

    layout = Layout(
        title='Hello Internet of Things 101 Data'
    )

    fig = Figure(data=[trace1], layout=layout)

    print py.plot(fig, filename='Hello Internet of Things 101 Plotly')

    i = 0
    stream = py.Stream(stream_token)
    stream.open()

    while True:
        stream_data = dataPlotly()
        stream.write({'x': i, 'y': stream_data})
        i += 1
        time.sleep(0.25)
コード例 #7
0
ファイル: Plots.py プロジェクト: cs327e-spring2016/LeeAndJD
def main():
  py.sign_in('JDGrillo', 'ymn6lb95az')
  trace = go.Scatter(
    x = [1991,1992,1993,1994],
    y = [2,4,3,9],
    mode = 'markers'
	)
  data = [trace]
  layout = go.Layout(
    xaxis=dict(
	  title="X-Axis",
      titlefont=dict(
        family='Arial, sans-serif',
        size = 18,
        color='grey'
		),
      showexponent='All'
    ),
	yaxis=dict(
      title="Y-Axis",
      titlefont=dict(
        family='Arial, sans-serif',
        size = 18,
        color='lightgrey'
		),
      showexponent='All'
    )
	
    )
  pplot = go.Figure(data = data, layout=layout)	
  py.plot(pplot,filename= 'scatter')
コード例 #8
0
ファイル: test_stream.py プロジェクト: fcolmenero/plotly.py
 def test_stream_validate_data(self):
     with self.assertRaises(exceptions.PlotlyError):
         py.sign_in(un, ak)
         my_stream = py.Stream(tk)
         my_stream.open()
         my_stream.write(dict(x=1, y=10, z=[1]))  # assumes scatter...
         my_stream.close()
コード例 #9
0
ファイル: main.py プロジェクト: soon/CodeforcesAPI
def main(argv):
    contest_id = int(argv[1])

    print('Loading problems...')
    problem_indices = [problem.index for problem in load_problems(contest_id)]
    print('Problems loaded')

    print('Loading hacks...')
    hacks = load_hacks(contest_id)
    print('Hacks loaded')
    grouped_by_verdict = sorted(group_hacks_by_verdict(hacks).items(),
                                key=lambda t: get_verdict_order(t[0]),
                                reverse=True)
    grouped_by_verdict_and_problems = [
        (t[0], sorted(get_hacks_count_by_problem(t[1], problem_indices).items()))
        for t in grouped_by_verdict
    ]

    bars = create_bars(grouped_by_verdict_and_problems)

    py.sign_in('Python-Demo-Account', 'gwt101uhh0')

    data = Data(list(bars))
    fig = plot_graph(data, contest_id)
    py.image.save_as(fig, 'awesome_image.png')
コード例 #10
0
ファイル: SRPTE_Catastrophic.py プロジェクト: rsmailach/SRPT
	def plotAvgNumJobsInSys(self):
		py.sign_in('mailacrs','wowbsbc0qo')
		trace0 = Scatter(x=NumJobsTime, y=AvgNumJobs)
		data = [trace0]
		layout = go.Layout(
			title='Average Number of Jobs Over Time',
			xaxis=dict(
				title='Time',
				titlefont=dict(
				family='Courier New, monospace',
				size=18,
				color='#7f7f7f'
			)
		),
			yaxis=dict(
				title='Number of Jobs',
				titlefont=dict(
				family='Courier New, monospace',
				size=18,
				color='#7f7f7f'
			)
		)
		)
		fig = go.Figure(data=data, layout=layout)
		unique_url = py.plot(fig, filename = 'SRPT_AvgNumJobs')
コード例 #11
0
ファイル: test_stream.py プロジェクト: fcolmenero/plotly.py
 def test_stream_validate_layout(self):
     with self.assertRaises(exceptions.PlotlyError):
         py.sign_in(un, ak)
         my_stream = py.Stream(tk)
         my_stream.open()
         my_stream.write(Scatter(x=1, y=10), layout=Layout(legend=True))
         my_stream.close()
コード例 #12
0
ファイル: e85-2015.py プロジェクト: littlejab/Project-PSIT
def e85_2015():
    """E85 year 2015 price graph"""
    py.sign_in("littlejab", "yblima8sc3")
    chart_min = go.Bar(
        x = ["Jan 15", "Feb 15", "Mar 15", "Apr 15", "May 15", "Jun 15"],
        y = [21.98, 22.67, 23.48, 22.81, 23.19, 23.37],
        name = "Min"
    )

    chart_avg = go.Bar(
        x = ["Jan 15", "Feb 15", "Mar 15", "Apr 15", "May 15", "Jun 15"],
        y = [21.98, 22.67, 23.48, 22.81, 23.19, 23.37],
        name = "Average"
    )

    chart_max = go.Bar(
        x = ["Jan 15", "Feb 15", "Mar 15", "Apr 15", "May 15", "Jun 15"],
        y = [21.98, 22.67, 23.48, 22.81, 23.19, 23.37],
        name = "Max"
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode = "group"
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename="E85 2015")
コード例 #13
0
ファイル: MyWindow.py プロジェクト: DRTooley/Hungarian
    def graph(self,gp):
        x1=[]
        y1=[]
        py.sign_in('Python-Demo-Account', 'gwt101uhh0')
        for row in gp:
            y1.append(row[0])
            x1.append(row[1])

        trace1 = Scatter(
            x=[x1[0], x1[1], x1[2], x1[3], x1[4]],
            y=[y1[0], y1[1], y1[2], y1[3], y1[4]],
            mode='markers',
            name='Runtime Data',
            text=['Run 1', 'Run 2', 'Run 3', 'Run 4', 'Run 5'],
            marker=Marker(
                color='rgb(164, 194, 244)',
                size=12,
                line=Line(
                    color='white',
                    width=0.5
                )
            )
        )
        data = Data([trace1])
        layout = Layout(
            title='IDA* Results',
            xaxis=XAxis(
                title='Depth'
            ),
            yaxis=YAxis(
                title='Nodes Expanded'
            )
        )
        fig = Figure(data=data, layout=layout)
        plot_url = py.plot(fig, filename='Run Time Data')
コード例 #14
0
ファイル: e10-2015.py プロジェクト: littlejab/Project-PSIT
def graph_e10_2015():
    """show graph of gas e10 price in year 2015 by min, avg, max"""
    import plotly.plotly as py
    import plotly.graph_objs as go
    py.sign_in('littlejab', 'yblima8sc3')
    chart_min = go.Bar(
        x=['Jan 15', 'Feb 15', 'Mar 15', 'Apr 15', 'May 15', 'Jun 15'],
        y=[28.04, 28.47, 29.35, 28.1, 29.08, 29.57],
        name='Min'
    )

    chart_avg = go.Bar(
        x=['Jan 15', 'Feb 15', 'Mar 15', 'Apr 15', 'May 15', 'Jun 15'],
        y=[28.04, 28.53, 29.36, 28.11, 29.08, 29.59],
        name='Average'
    )

    chart_max = go.Bar(
        x=['Jan 15', 'Feb 15', 'Mar 15', 'Apr 15', 'May 15', 'Jun 15'],
        y=[28.04, 28.67, 29.39, 28.17, 29.13, 29.64],
        name='Max'
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode='group'
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename='E10 2015')
コード例 #15
0
  def plotLy(self):
    userID = self.userName_box.text()
    userKey = self.userKey_box.text()
    py.sign_in(userId, userKey)                                                          # sign into plot.ly

    f2 = open('spectra.dat', 'r')                                                                            # open the spectra.dat file for reading into the graph
    lines = f2.readlines()                                                                                      # read the entire file into a single variable
    f2.close()                                                                                                      # close the spectra.dat file

    x1 = []                                                                                                           # initialize the X coord
    y1 = []                                                                                                           # initialize the y coord
    for line in lines:
      p = line.split()                                                                    # scan the rows of the file stored in lines, and put the values
      if len(p) != 2:
        print("error")
        continue
      x1.append(float(p[0]))                                                              #      into some variables:
      y1.append(float(p[1]))

    xv = np.array(x1)                                                                                               # set the array for x
    yv = np.array(y1)                                                                                               # set the array for y

    timestr = time.strftime("%Y%m%d%H%M%S")
    plotly_trace1 = Scatter(x=xv, y=yv)                                                    # add data to plot.ly array
    plotly_data = Data([plotly_trace1])                                                      # send data to plot.ly
    plot_url = py.plot(plotly_data, filename='ramanPi' + timestr)                                          # create graph and display on plot.ly
コード例 #16
0
def e85_12_to_15():
    py.sign_in("littlejab", "yblima8sc3")
    chart_min = go.Bar(
        x = ["2012", "2013", "2014", "2015"],
        y = [22.22, 22.73, 24.11, 22.92],
        name = "Min"
    )

    chart_avg = go.Bar(
    x = ["2012", "2013", "2014", "2015"],
    y = [22.23, 22.74, 24.11, 22.92],
        name = "Average"
    )

    chart_max = go.Bar(
        x = ["2012", "2013", "2014", "2015"],
        y = [22.23, 22.74, 24.11, 22.92],
        name = "Max"
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode = "group"
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename = "E85 All Year")
コード例 #17
0
def graph_gas95_allyears():
    """show graph of gas95 price allyears by min, avg, max"""
    import plotly.plotly as py
    import plotly.graph_objs as go
    py.sign_in('littlejab', 'yblima8sc3')
    chart_min = go.Bar(
        x=['2012', '2013', '2014', '2015'],
        y=[46.27, 46.41, 46.43, 34.87],
        name='Min'
    )

    chart_avg = go.Bar(
        x=['2012', '2013', '2014', '2015'],
        y=[46.42, 46.66, 46.73, 35.17],
        name='Average'
    )

    chart_max = go.Bar(
        x=['2012', '2013', '2014', '2015'],
        y=[47.19, 46.91, 46.92, 35.37],
        name='Max'
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode='group'
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename='Gasoline 95 All Year')
コード例 #18
0
def graph_allyears():
    """show graph of gas e10 price allyears by min, avg, max"""
    import plotly.plotly as py
    import plotly.graph_objs as go
    py.sign_in('littlejab', 'yblima8sc3')
    chart_min = go.Bar(
        x=['2012', '2013', '2014', '2015'],
        y=[37.94, 38.8, 38.83, 28.77],
        name='Min'
    )

    chart_avg = go.Bar(
        x=['2012', '2013', '2014', '2015'],
        y=[37.96, 38.89, 38.85, 28.79],
        name='Average'
    )

    chart_max = go.Bar(
        x=['2012', '2013', '2014', '2015'],
        y=[38.01, 38.95, 38.94, 28.84],
        name='Max'
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode='group'
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename='E10 All Year')
コード例 #19
0
ファイル: diesel 2014.py プロジェクト: littlejab/Project-PSIT
def diesel_2014():
    """Display monthly chart for diesel price in Thailand 2014."""
    import plotly.plotly as py
    import plotly.graph_objs as go
    py.sign_in('littlejab', 'yblima8sc3')
    chart_min = go.Bar(
        x = ['Jan 14', 'Feb 14', 'Mar 14', 'Apr 14', 'May 14', 'Jun 14', 'Jul 14', 'Aug 14', \
        'Sep 14', 'Oct 14', 'Nov 14', 'Dec 14'],
        y = [29.99, 29.99, 29.99, 29.99, 29.99, 29.91, 29.85, 29.86, 29.99, 29.66, 29.41, 27.6],
        name = 'Min'
    )
    chart_avg = go.Bar(
        x = ['Jan 14', 'Feb 14', 'Mar 14', 'Apr 14', 'May 14', 'Jun 14', 'Jul 14', 'Aug 14', \
        'Sep 14', 'Oct 14', 'Nov 14', 'Dec 14'],
        y = [29.99, 29.99, 29.99, 29.99, 29.99, 29.91, 29.85, 29.86, 29.99, 29.66, 29.42, 27.64],
        name = 'Average'
    )
    chart_max = go.Bar(
        x = ['Jan 14', 'Feb 14', 'Mar 14', 'Apr 14', 'May 14', 'Jun 14', 'Jul 14', 'Aug 14', \
        'Sep 14', 'Oct 14', 'Nov 14', 'Dec 14'],
        y = [29.99, 29.99, 29.99, 29.99, 30.05, 30.01, 29.85, 29.86, 29.99, 29.66, 29.42, 27.91],
        name = 'Max'
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(barmode = 'group')
    fig = go.Figure(data = data, layout = layout)
    plot_url = py.plot(fig, filename = 'Diesel 2014')
コード例 #20
0
ファイル: xplotly.py プロジェクト: xe1gyq/core
    def __init__(self, title):
        self.title = title
        self.directorycurrent = os.path.dirname(os.path.realpath(__file__))
        self.directoryconfiguration = self.directorycurrent + '/../configuration/'
        self.configuration = ConfigParser.ConfigParser()
        self.credentialspath = self.directoryconfiguration + "credentials.config"
        self.configuration.read(self.credentialspath)
        self.username = self.configuration.get('plotly','username')
        self.apikey = self.configuration.get('plotly','apikey')
        self.streamtoken = self.configuration.get('plotly','streamtoken')

        py.sign_in(self.username, self.apikey)

        stream_data = Scatter(
            x=[],
            y=[],
            stream=dict(
                token=self.streamtoken,
            )
        )

        layout = Layout(
            title = self.title
        )

        this = Figure(data=[stream_data], layout=layout)
        py.plot(this, filename=self.title, auto_open=False)

        self.stream = py.Stream(self.streamtoken)
        self.stream.open()
        time.sleep(5)
コード例 #21
0
ファイル: gmail-plotly.py プロジェクト: dpshelio/gmail-plotly
def main():
    parser = argparse.ArgumentParser(parents=[o2c.tools.argparser])
    parser.add_argument('--no-plot', help="don't plot", action='store_true')
    flags = parser.parse_args()

    gmail_service = g_authorized(flags)
    searches = {'primary_unread': 'category:primary is:unread',
                'primary_total': 'category:primary',
                'inbox_unread': 'in:inbox is:unread',
                'inbox_total': 'in:inbox'}
    counts = {key: count_threads(gmail_service, search) for key, search in searches.iteritems()}

    if flags.no_plot: return

    plotly_key = grab(PLOTLY_KEY_FILE)
    plotly_username = grab(PLOTLY_USERNAME_FILE)

    polite_names = {'primary_unread': 'Primary inbox, unread',
                    'primary_total': 'Primary inbox',
                    'inbox_unread': 'Inbox, unread',
                    'inbox_total': 'Inbox'}

    now = datetime.datetime.now()
    data = go.Data([go.Scatter(x=[now], y=[counts[key]], mode='lines+markers', name=polite_names[key]) for key in counts])
    layout = go.Layout(title="Emails in inbox")
    fig = go.Figure(data=data, layout=layout)
 
    plotly.sign_in(plotly_username, plotly_key)
    url = plotly.plot(fig, filename='gmail-plotly', fileopt='extend', world_readable=PLOTLY_WORLD_READABLE, auto_open=False)
    print url
コード例 #22
0
def sign_in(file_name):
    '''read credentials from config file, and log in to Plot.ly'''
    conf_parser = ConfigParser()
    conf_parser.read(file_name)
    username = conf_parser.get('authentication', 'username')
    api_key = conf_parser.get('authentication', 'api_key')
    py.sign_in(username, api_key)
コード例 #23
0
ファイル: gas-95-2013.py プロジェクト: littlejab/Project-PSIT
def graph_gas95_2013():
    """show graph of gas95 price in year 2013 by min, avg, max"""
    import plotly.plotly as py
    import plotly.graph_objs as go
    py.sign_in('littlejab', 'yblima8sc3')
    chart_min = go.Bar(
        x=['Jan 13', 'Feb 13', 'Mar 13', 'Apr 13', 'May 13', 'Jun 13', 'Jul 13', 'Aug 13', \
        'Sep 13', 'Oct 13', 'Nov 13', 'Dec 13'],
        y=[46.27, 48.2, 47.33, 45.03, 44.79, 45.91, 47.4, 46.94, 46.58, 46.09, 45.95, 47.26],
        name='Min'
    )

    chart_avg = go.Bar(
        x=['Jan 13', 'Feb 13', 'Mar 13', 'Apr 13', 'May 13', 'Jun 13', 'Jul 13', 'Aug 13', \
            'Sep 13', 'Oct 13', 'Nov 13', 'Dec 13'],
        y=[47.03, 48.41, 47.33, 45.05, 44.82, 46.02, 47.62, 46.98, 47.06, 46.4, 46.55, 47.65],
        name='Average'
    )

    chart_max = go.Bar(
        x=['Jan 13', 'Feb 13', 'Mar 13', 'Apr 13', 'May 13', 'Jun 13', 'Jul 13', 'Aug 13', \
            'Sep 13', 'Oct 13', 'Nov 13', 'Dec 13'],
        y=[48.27, 48.64, 47.33, 45.16, 44.88, 46.14, 47.68, 47.05, 47.38, 46.6, 46.83, 47.83],
        name='Max'
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode='group'
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename='Gasoline 95 2013')
コード例 #24
0
    def plotly(self, rc):
        import plotly.plotly as py
        from plotly.graph_objs import Layout,Figure
        def df_to_iplot(inp):
            
            '''
            Coverting a Pandas Data Frame to Plotly interface
            '''
            df = inp.dataframe
            del df["est"]
            lines={}
            x = df.columns.values[2:]
            for i in range(len(df)):
                row = df.iloc[i]
                key = row["industry"]
                lines[key]={}
                lines[key]["x"]=x
                lines[key]["y"]=row[2:].values
                lines[key]["name"]=key
                #Appending all lines
            lines_plotly=[lines[key] for key in lines]
            return lines_plotly

        py.sign_in("pyrrho", "04n3iw0mae")

        for inp in rc.get_inputs():
            df = inp.dataframe
            data = df_to_iplot(inp)
            layout = Layout(
                    title = inp.basename
                    )
            fig = Figure(data=data, layout=layout)
            unique_url = py.plot(data, filename = inp.basename, auto_open=False)
            log.status("plot for %s found at %s" % (inp.basename, unique_url))
        yield rc         
コード例 #25
0
ファイル: plotlyf.py プロジェクト: MonsieurV/PiRadBox
def forward(configuration, readings):
    print("Plotlying... {0}.".format(readings))
    # TODO We need a process running in continue to stream
    # to Plotly. We really do need to implement the forwarding
    # with an independant app, dispatching readings coming from a broker.
    py.sign_in(configuration['plotly']['username'],
        configuration['plotly']['apiKey'])
    url = py.plot(
        Figure(
            layout=Layout(
                title=configuration['plotly']['plotTitle'],
                xaxis=dict(title='Timestamp'),
                yaxis=dict(title='Dose (uSv/h)')),
            data=Data([
                Scatter(
                    x=[], y=[],
                    mode='lines',
                    stream=Stream(
                        token=configuration['plotly']['streamingToken']))])),
        filename=configuration['plotly']['plotTitle'])
    print("Plotly graph URL: {0}".format(url))
    stream = py.Stream(configuration['plotly']['streamingToken'])
    stream.open()
    stream.write(dict(x=readings['timestamp'], y=readings['uSvh']))
    stream.close()
    print("Plotly Ok.")
コード例 #26
0
ファイル: e85-2014.py プロジェクト: littlejab/Project-PSIT
def e85_2014():
    """E85 year 2014 price graph"""
    py.sign_in("littlejab", "yblima8sc3")
    chart_min = go.Bar(
        x = ["Jan 14", "Feb 14", "Mar 14", "Apr 14", "May 14", "Jun 14", "Jul 14", "Aug 14", \
            "Sep 14", "Oct 14", "Nov 14", "Dec 14"],
        y = [24.45, 24.38, 24.52, 24.57, 24.70, 24.61, 24.51, 24.28, 24.28, 23.48, 22.88, 22.65],
        name = "Min"
    )

    chart_avg = go.Bar(
     x = ["Jan 14", "Feb 14", "Mar 14", "Apr 14", "May 14", "Jun 14", "Jul 14", "Aug 14", \
        "Sep 14", "Oct 14", "Nov 14", "Dec 14"],
     y = [24.45, 24.38, 24.52, 24.56, 24.67, 24.61, 24.51, 24.28, 24.28, 23.48, 22.88, 22.65],
     name = "Average"
    )

    chart_max = go.Bar(
        x = ["Jan 14", "Feb 14", "Mar 14", "Apr 14", "May 14", "Jun 14", "Jul 14", "Aug 14", \
            "Sep 14", "Oct 14", "Nov 14", "Dec 14"],
        y = [24.45, 24.38, 24.38, 24.52, 24.57, 24.70, 24.61, 24.51, 24.28, 23.48, 22.88, 22.65],
        name = "Max"
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode = "group"
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename = "E85 2014")
コード例 #27
0
def create_heroes_dmg_cost_graphs():
    heroes_data = read_heroes_dmg_cost_data('./Output/Heroes_Dmg_Cost')
    plotly.sign_in("haukurpalljonsson", "dr78f5q3yh")
    dps_data = []
    dps_data_total = []
    for x in range(1, len(heroes_data) + 1):
        axis_levels = []
        axis_dps_increase = []
        axis_dps_increase_total = []
        hero_key = str(x)
        #I know (has to be fixed) that the first level inserted is 1
        for y in range(1, int(len(heroes_data[hero_key])/2) + 1):
            level_key = str(y)
            level_key_total = str(y) + '+'
            axis_levels.insert(y-1, y)
            axis_dps_increase.insert(y-1, int(heroes_data[hero_key][level_key][1]))
            axis_dps_increase_total.insert(y-1, int(heroes_data[hero_key][level_key_total][1]))

        #moa

        dps_trace = Scatter(x=axis_levels, y=axis_dps_increase)
        dps_data.append(dps_trace)
        dps_trace_total = Scatter(x=axis_levels, y=axis_dps_increase_total)
        dps_data_total.append(dps_trace_total)

    print(plotly.plot(dps_data, filename='dps_increase'))
    print(plotly.plot(dps_data_total, filename='dps_increase_total'))
コード例 #28
0
    def setup(self):
        my_creds = tls.get_credentials_file()                  # read credentials
        py.sign_in(my_creds['username'], my_creds['api_key'])  # (New syntax!) Plotly sign in
        tls.embed('streaming-demos','6')

        my_stream_ids = tls.get_credentials_file()['stream_ids']

        # Get stream id from stream id list 
        self.my_stream_id = my_stream_ids[0]

        # Make instance of stream id object 
        my_stream = Stream(token=self.my_stream_id,  # N.B. link stream id to 'token' key
                           maxpoints=200)        # N.B. keep a max of 80 pts on screen


        # Initialize trace of streaming plot by embedding the unique stream_id
        my_data = Data([Scatter(x=[],
                                y=[],
                                mode='lines+markers',
                                stream=my_stream)]) # embed stream id, 1 per trace

        # Add title to layout object
        my_layout = Layout(title='Quake monitor')

        # Make instance of figure object
        my_fig = Figure(data=my_data, layout=my_layout)

        # Initialize streaming plot, open new tab
        unique_url = py.plot(my_fig, filename='qm_first-stream')
コード例 #29
0
def main():
    rawData = loadData(PATH_TO_DATA)

    rawData = splitDataByArrangement(rawData)
    avgData = averageArrangmentData(rawData)

    # graphData = createTracesForRaw(rawData, 'loopLength','audio_time')
    graphData = createTraceForAvg(avgData, 'audio_time', 'totalTime', name="audio")
    graphData += createTraceForAvg(avgData, 'init_time', 'totalTime', name="init")
    graphData += createTraceForAvg(avgData, 'other_time', 'totalTime', name="other")
    graphData += createTraceForAvg(avgData, 'non_time', 'totalTime', name="non")

    layout = go.Layout(
        title='Total Rendering Time vs Audio/Initialization Time',
        hovermode='closest',
        xaxis=dict(
            title='Time Spent on Stage (s)'
        ),
        yaxis=dict(
            title='Total Rendering Time (s)'
        ),
    )

    py.sign_in("MysteryDate", "a6fd7sm5jr")

    fig = go.Figure(data=graphData, layout=layout)
    plot_url = py.plot(fig, filename="Sources of Rendering Time")
コード例 #30
0
ファイル: e85-2013.py プロジェクト: littlejab/Project-PSIT
def e85_2013():
    """E85 year 2013 price graph"""
    py.sign_in("littlejab", "yblima8sc3")
    chart_min = go.Bar(
        x = ["Jan 13", "Feb 13", "Mar 13", "Apr 13", "May 13", "Jun 13", "Jul 13", "Aug 13", \
            "Sep 13", "Oct 13", "Nov 13", "Dec 13"],
        y = [21.83, 22.76, 22.91, 21.88, 21.82, 22.66, 23.57, 23.19, 23.27, 22.98, 23.19, 23.78],
        name = "Min"
    )

    chart_avg = go.Bar(
        x = ["Jan 13", "Feb 13", "Mar 13", "Apr 13", "May 13", "Jun 13", "Jul 13", "Aug 13", \
            "Sep 13", "Oct 13", "Nov 13", "Dec 13"],
        y = [21.83, 22.84, 22.91, 21.88, 21.82, 22.66, 23.57, 23.19, 23.27, 22.98, 23.19, 23.78],
        name = "Average"
    )

    chart_max = go.Bar(
        x = ["Jan 13", "Feb 13", "Mar 13", "Apr 13", "May 13", "Jun 13", "Jul 13", "Aug 13", \
            "Sep 13", "Oct 13", "Nov 13", "Dec 13"],
        y = [21.83, 22.89, 22.91, 21.88, 21.82, 22.66, 23.57, 23.19, 23.27, 22.98, 23.19, 23.78],
        name = "Max"
    )
    data = [chart_min, chart_avg, chart_max]
    layout = go.Layout(
        barmode = "group"
    )
    fig = go.Figure(data=data, layout=layout)
    plot_url = py.plot(fig, filename = "E85 2013")
コード例 #31
0
from __future__ import print_function
from future.standard_library import install_aliases
import requests

install_aliases()  # not sure what this does...

import plotly.plotly as py
from plotly.graph_objs import *

url = "https://staging.kitomba.com/k1/clients_ajax/get_client_appointments_info_for_day/Today/93895ccd5153edb2f7b09193b9225f89/all"
token = "8623a3ff07832d2fe4d7079aa811745d"
headers = {'Token': token}
py.sign_in('paul.sinclair', '20xGivFuRABOeYkaCyTq')

# {'id': '654ceea0-564f-4160-841c-e4d3ee330134', 'timestamp': '2017-06-22T05:14:41.26Z', 'lang': 'en',
#  'result': {'source': 'agent', 'resolvedQuery': 'invoice', 'speech': '', 'action': 'test2', 'actionIncomplete': False,
#             'parameters': {'token': 'fb83a162598f007adc00609d6adfc5a7'}, 'contexts': [{'name': 'logged_in',
#                                                                                        'parameters': {
#                                                                                            'token.original': '',
#                                                                                            'password': '******',
#                                                                                            'email.original': '*****@*****.**',
#                                                                                            'password.original': 'hard24get',
#                                                                                            'email': '*****@*****.**',
#                                                                                            'token': 'fb83a162598f007adc00609d6adfc5a7'},
#                                                                                        'lifespan': 497},
#                                                                                       {'name': 'token', 'parameters': {
#                                                                                           'token.original': '',
#                                                                                           'password': '******',
#                                                                                           'email.original': '*****@*****.**',
#                                                                                           'password.original': 'hard24get',
#                                                                                           'email': '*****@*****.**',
コード例 #32
0
ファイル: dbinit.py プロジェクト: CPorter81/xAduioEmberMobile
import billboard
import plotly.plotly as py
import plotly.graph_objs as go
from datetime import datetime, timedelta
from app import db, models
import dateutil.parser as parser 
from sqlalchemy import exists, desc
import config as Config


py.sign_in(Config.user, Config.api_key)
song_id_max=0
artist_id_max=0
def insertsongs(NAMEOFGENRE):
    global song_id_max
    global artist_id_max


    chart = billboard.ChartData(NAMEOFGENRE, date = '2016-01-01')
    while(chart.date < '2017-07-24'):
        
        for i in chart:
            date = datetime.strptime(chart.date, '%Y-%m-%d')
            artist = i.artist
            print (i.title)
            print (artist)
            
            #-------------Calculating Point Position------------------------------
            Points = 101
            for b in range(i.rank):
                Points = Points - 1
コード例 #33
0
from flask import render_template, flash, request, url_for, redirect
from flask.ext.login import login_user, logout_user, login_required, current_user
from .forms import LoginForm, RegisterForm, CreateLinkForm, CustomLinkForm
from . import app, db
from .models import User, Link, Custom, Click
from datetime import datetime
from sqlalchemy import desc
import plotly.plotly as py
from plotly.graph_objs import *

py.sign_in('bodandly', 'plmh01cnfk')


def flash_errors(form, category="warning"):
    '''Flash all errors for a form.'''
    for field, errors in form.errors.items():
        for error in errors:
            flash("{0} - {1}".format(getattr(form, field).label.text, error),
                  category)


@app.route('/')
def index():
    links = Link.query.order_by(Link.id).all()

    return render_template('index.html',
                           links=links,
                           base_url=request.url_root)


@app.route('/login', methods=['GET', 'POST'])
コード例 #34
0
import csv
import plotly.plotly as py
from plotly.graph_objs import *
py.sign_in('aul99999', 'YJdLMTY53oqOanHFhxrw')

with open("ProjectPSIT.csv", "r") as database:
    reader = csv.DictReader(database)
    month = {}
    num = 1
    for i in reader:
        month.setdefault(num, [i["YEAR"], i["2557"]])
        num += 1

    xReader = []
    yReader = []
    for i in sorted(month):
        xReader.append(month[i][0])
        yReader.append(int(month[i][1]))

trace1 = Scatter(x=xReader, y=yReader)

data = Data([trace1])
plot_url = py.plot(data)
コード例 #35
0
import plotly.plotly as py
from plotly.graph_objs import *
py.sign_in('Happy_Das', 'gqFHrnV4u2yQkUdckBtD')
X, Y = [], []
for line in open(
        '../Results/Capital_Country/Main_Capital_Country_Average_Accuracy.txt',
        'r'):
    values = [str(s) for s in line.split()]
    X.append(values[0])
    Y.append(values[1])

data1 = {
    "x": X,
    "y": Y,
    "name": "Accuracy for Country-Capital",
    "type": "scatter"
}

X, Y = [], []
for line in open(
        '../Results/Currency_Country/Main_Currency_Country_Average_Accuracy.txt',
        'r'):
    values = [str(s) for s in line.split()]
    X.append(values[0])
    Y.append(values[1])

data2 = {
    "x": X,
    "y": Y,
    "name": "Accuracy for Country-Currency",
    "type": "scatter"
コード例 #36
0
def init():
    py.sign_in('PythonTest', '9v9f20pext')
コード例 #37
0
import sys
import gzip
import glob
import os
import re
import numpy as np
import pandas as pd
from scipy.stats import linregress
import matplotlib.pyplot as plt
import deepOceanTemp
import netCDF4 as nc

import plotly.plotly as py  # for sending things to plotly
import plotly.graph_objs as go
import plotly.tools as tls  # for mpl, config, etc.
py.sign_in('JeremyFyke', 'u28du98cke')
plot_online = 0  #if 0, then prints static plots locally.

plot_GLC_timeseries = 1
plot_ocean_temperature_timeseries = 0
plot_AMOC_timeseries = 0
plot_calving_flux = 1

suffix = ''
suffix2 = '_restoring'
user_space = 'jfyke'

output_dir = 'plots' + suffix
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
コード例 #38
0
ファイル: test_stream.py プロジェクト: EvaSchmid/Test
 def setUp(self):
     super(TestStreaming, self).setUp()
     py.sign_in(un, ak, **config)
コード例 #39
0
import time
import pandas as pd
import numpy as np
import plotly.plotly as py
from plotly.graph_objs import *
import deepLearningTest
import paramSVR
from sklearn import preprocessing

# py.sign_in('sunjiannankai', 'r8kdW8nbxiw5HJeCehBj')

py.sign_in('JianSun', 'AmAEUGYZCUR2D1dxFCZk')

if __name__ == '__main__':
    funNum = 3  # the number of function for deep learning method 1:normal,2:more neurons 3: more layers
    typeTrainDB = 3  # 1: only OTUs 2: only easy_get para 3: OUT + easy_get
    start = time.time()
    # targetNormal = True  # the target is normalized or not

    isRegression = False
    isCheckPara = False
    targetNormal = isCheckPara
    if typeTrainDB == 1:
        figureTitle = "The reliability of SVR, Random Forest and NN. Use OTU only"
    elif typeTrainDB == 2:
        figureTitle = "The reliability of SVR, Random Forest and NN. Use Easy-get parameters only"
    elif typeTrainDB == 3:
        figureTitle = "The reliability of SVR, Random Forest and NN. Use both OTU and Easy parameters"
    targetList = ['salinity']
    # targetList = ['salinity', 'Depth', 'Temperature', 'O2', 'PO4', 'SiO2', 'NO2', 'NO3']
コード例 #40
0
ファイル: bottleplot.py プロジェクト: HayangSUZ/OTTO
import os
from bottle import run, template, get, post, request

import plotly.plotly as py
from plotly.graph_objs import *

import json

# grab username and key from config/data file
with open('data.json') as config_file:
    config_data = json.load(config_file)
username = config_data["user"]
key = config_data["key"]

py.sign_in(username, key)


@get('/plot')
def form():
    return template('template', title='Plot.ly Graph')


@post('/plot')
def submit():
    # grab data from form
    Y01 = request.forms.get('Y01')
    Y02 = request.forms.get('Y02')
    Y03 = request.forms.get('Y03')
    Y04 = request.forms.get('Y04')
    Y11 = request.forms.get('Y11')
    Y12 = request.forms.get('Y12')
コード例 #41
0
import serial, time  # Serial and Time
import datetime  # Current Date and Time
from webiopi.devices.serial import Serial  # Webiopi Serial
import webiopi  # Webiopi Library
import plotly.plotly as py  # plotly library
from plotly.graph_objs import Scatter, Layout, Figure, Data, Stream, YAxis

###############################################################
##################### Sets up plotly details ##################

username = '******'
api_key = 'k53c99f7d1'
stream_token_temperature = 'iuqh3xt5ph'
stream_token_lightlevel = 'vlx5vddak3'

py.sign_in('zaneshaq', 'k53c99f7d1')

# JSON code for plotly graph
trace_temperature = Scatter(
    x=[],
    y=[],
    name='Temp',
    stream=Stream(token=stream_token_temperature  # Sets up temperature stream
                  ),
    yaxis='y')

trace_lightlevel = Scatter(
    x=[],
    y=[],
    name='Light %',
    stream=Stream(token=stream_token_lightlevel  # Sets up Lightlevel stream
コード例 #42
0
title="A circular graph associated to Eurovision Song Contest, 2015<br>Data source:"+\
"<a href='http://www.eurovision.tv/page/history/by-year/contest?event=2083#Scoreboard'> [1]</a>"
layout=Layout(title= title,
              font= Font(size=12),
              showlegend=False,
              autosize=False,
              width=width,
              height=height,
              xaxis=XAxis(axis),
              yaxis=YAxis(axis),          
              margin=Margin(l=40,
                            r=40,
                            b=85,
                            t=100,
                          ),
              hovermode='closest'#,
              #annotations=Annotations([make_annotation(anno_text1, -0.07), 
                                  #     make_annotation(anno_text2, -0.09),
                                  #     make_annotation(anno_text3, -0.11)]
                                  #   )
              )
data=Data(lines+edge_info+[trace2])
fig=Figure(data=data, layout=layout)
py.sign_in('shivm', 'V7rWwhWSEo2YE0w3J73A') 
py.plot(fig, filename='Eurovision-15') 
                                
#Write results
results.to_csv('X:/Projects/IITDelhi/Paths/expresults2.csv', index=False)

math.
コード例 #43
0
ファイル: contributors.py プロジェクト: wragge/trove-sketches
Quick Python sketch to graph numbers of Trove contributors and resources 
from each Australian state against the population of that state.

Graphs are created using Plotly's Python API.

Add your Trove & Plotly credentials to credentials_fillmein.py and
save as credentials.py.

"""
import requests
import plotly.plotly as py
from plotly.graph_objs import *

from credentials import TROVE_API_KEY, PLOTLY_ID, PLOTLY_KEY

py.sign_in(PLOTLY_ID, PLOTLY_KEY)

#Trove API url to get contributor details
TROVE_URL = 'http://api.trove.nla.gov.au/contributor/?encoding=json&reclevel=full&key={}'

#Mapping NUC keys to state names
STATES = {
    'A': 'ACT',
    'N': 'NSW',
    'X': 'NT',
    'Q': 'Qld',
    'S': 'SA',
    'T': 'Tas',
    'V': 'Vic',
    'W': 'WA'
}
コード例 #44
0
def signin():
    py.sign_in(os.environ["PLOTLY_USERNAME"], os.environ["PLOTLY_API_KEY"])
コード例 #45
0
from plotly.graph_objs import *

df = pd.read_csv(
    "/Users/Jean/Documents/Software Engineering/UFG/mestrado/ARP/datasets/crimes-in-chicago/Chicago_Crimes_2012_to_2017.csv",
    sep=",")
#df = pd.read_csv("/Users/Jean/Documents/Software Engineering/UFG/mestrado/ARP/finalProject/datasets/smalldatasetcrimes.csv",sep=",")
df = df[df.Year == 2016]
df = df[df['Primary Type'] == 'HOMICIDE']
grouped = df.groupby(['Latitude', 'Longitude'
                      ])['Case Number'].count().reset_index(name="count")
grouped = grouped.sort('count', ascending=False)

print(grouped)

mapbox_access_token = 'pk.eyJ1IjoiamVhbmxrcyIsImEiOiJjaXo1dThlbWswM3VwMndtbmhyNTlyazc3In0.j1ezMv-foA4UUPnJz8DYEA'
py.sign_in('jeanlks', '360cSGj1UBUxHAfiDd3M')
data = Data([
    Scattermapbox(
        lat=grouped["Latitude"],
        lon=grouped["Longitude"],
        mode='markers',
        marker=Marker(size=grouped['count'] * 10),
        text=grouped['count'],
    )
])
layout = Layout(
    autosize=True,
    hovermode="closest",
    mapbox=dict(accesstoken=mapbox_access_token,
                bearing=0,
                center=dict(lat=41.88, lon=-87.62),
コード例 #46
0
import plotly.plotly as py
import plotly.graph_objs as go
import plotly
import csv
import collections
import random
from collections import Counter
from operator import itemgetter
import statistics
import datetime
from functools import reduce

plotly.tools.set_credentials_file(username='******',
                                  api_key='CvmqbRb7CXD5VgwhRzQV')
py.sign_in("kristelle", "CvmqbRb7CXD5VgwhRzQV")

reader = csv.reader(open(
    '/Users/macbook/Desktop/FYP/files/AlphaBayMarket-transactions/AlphaBay_transactions.csv',
    'rt'),
                    delimiter=',')

dictionary = []

transactions = []
for row in reader:
    if len(row) == 7 and row[0] != 'date' and row[2] != '':
        transactions.append(row)

# Sort transactions by date
transactions = sorted(transactions, key=lambda x: x[0])
コード例 #47
0
ファイル: s.py プロジェクト: aarora79/datavis
import os
import pandas as pd
arr = next(os.walk('.'))[2]
ts_files = [f for f in arr if '.csv' in f]
print(arr)
print(len(ts_files))

import plotly.plotly as py
from plotly.graph_objs import *
py.sign_in('aa1603', 'PHHAVAgjg4NQgXLqPTtb')

layout = {
    "autosize": False,
    "height": 1000,
    "showlegend": False,
    "title":
    "<b>Timeseries for number Starbucks stores 2013-2016</b><br>Countries with the maximum percentage increase in number Starbucks stores. \
            <br>Clean data and code available <a href='http://aa1603.georgetown.domains/ANLY503/Portfolio/live/plotly_sparkline_starbucks/'>here</a>\
            <br><i>Only includes countries with at least 25 stores as of November 2016.</i>",
    "width": 800
}

traces = []
count = 1
for f in ts_files:
    df = pd.read_csv(f)
    trace = {
        "x": df['x'],
        "y": df['y'],
        "fill": "tozeroy",
        "line": {
コード例 #48
0
import ROOT as R
import os, sys, glob, json
import matplotlib.pyplot as plt
import plotly.plotly as py
from plotly.tools import FigureFactory as FF
py.sign_in('username', 'api_key')


def skipCategories(d):
    newd = {}
    for key in d.keys():
        nkey = key
        #        if "Jets" in key:
        #            nkey = nkey.replace("Jets", "J")
        #        if "Jet" in key:
        #            nkey = nkey.replace("Jet", "J")
        #        if "Tight" in key:
        #            nkey = nkey.replace("Tight", "T")
        #        if "Loose" in key:
        #            nkey = nkey.replace("Loose", "L")
        if "Combination" in key:
            #          nkey = nkey.replace("Combination", "C")
            newd[nkey] = d[key]

    return newd


def main():
    template_limits = "/Users/vk/software/Analysis/files/limits_higsscombined_results/v0p6_20160824_1100/76X__Cert_271036-278808_13TeV_PromptReco_Collisions16_JSON_NoL1T__Mu22"
    analytic_limits = "/Users/vk/software/Analysis/files/limits_higsscombined_results/v0p5_20160824_1100/76X__Cert_271036-278808_13TeV_PromptReco_Collisions16_JSON_NoL1T__Mu22"
    template_pattern = "explimits__templates*.json"
コード例 #49
0
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
from bs4 import BeautifulSoup
import urllib2
import numpy as np
import pandas as pd
import plotly.plotly as py
from plotly.graph_objs import *
py.sign_in("*PLOTLY USERNAME HERE", "PLOTLY API HERE")


# test connection
def connectSQL():
    db_config = read_db_config()

    try:
        print('Connecting to MySQL database...')
        conn = MySQLConnection(**db_config)

        if conn.is_connected():
            print('Connection established.')
        else:
            print('Connection failed.')

    except Error as error:
        print(error)

    finally:
        conn.close()
        print('Connection closed.')
コード例 #50
0
import pandas as pd
from dateutil import parser
import plotly.plotly as py
import plotly.graph_objs as go

# Larkmead blocks
# acres) = 44.66

# TODO: Task a parameter ('detection')
# TODO: Reinstate daytotal

# Input log file
logpath = 'logs/larkmead_detection.log'

# Plotly credentials
py.sign_in('agriselwyn', '0nM9F4CYVWKsI8lIwk9X')

with open(logpath, 'r') as logfile:
    data_in = logfile.read()

# Create a dictionary of data frames, along with a total cumulative data frame
sessions = set([
    col.replace('detection:', '').strip()
    for col in re.findall('detection:[a-z0-9\-]+', data_in)
])

# Initialization
frames = dict.fromkeys(sessions)
for c in frames.keys():
    frames[c] = pd.DataFrame(columns=['Date', 'Remaining'])
コード例 #51
0
import plotly.plotly as py
import numpy as np
import matplotlib.pyplot as plt

py.sign_in('isak.falk', 'c5db1lskr9')

mpl_fig = plt.figure()

x = np.random.randn(20)
y = np.random.randn(20)

plt.scatter(x, y)

py.plot_mpl(mpl_fig, filename="plotly_figure")
コード例 #52
0
ファイル: map_plot.py プロジェクト: waiweran/health-316
from plotly import plotly, tools, exceptions
import requests
import json

username = '******'
accountkey = 'fjFaA6Af6vDjuZmjLNa0'

plotly.sign_in(username, accountkey)
auth = requests.auth.HTTPBasicAuth(username, accountkey)
headers = {'Plotly-Client-Platform': 'python'}


def make_states_plot(plot_locations, plot_data, tooltip_labels,
                     colorscale_label, plot_title):
    scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
               [0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]

    data = [
        dict(type='choropleth',
             colorscale=scl,
             autocolorscale=False,
             locations=plot_locations,
             z=plot_data,
             locationmode='USA-states',
             text=tooltip_labels,
             marker=dict(line=dict(color='rgb(0,0,0)', width=2)),
             colorbar=dict(title=colorscale_label))
    ]

    layout = dict(
        title=plot_title,
コード例 #53
0
import plotly.plotly as py
from plotly.graph_objs import *
from getpass import getpass
import numpy as np
import pandas as pd

df = pd.read_csv('transcount.csv')
df = df.groupby('year').aggregate(np.mean)

gpu = pd.read_csv('gpu_transcount.csv')
gpu = gpu.groupby('year').aggregate(np.mean)

df = pd.merge(df, gpu, how='outer', left_index=True, right_index=True)
df = df.replace(np.nan, 0)

api_key = getpass()

# Change the user to your own username
py.sign_in('LearningPythonDataAnalysis', api_key)

counts = np.log(df['trans_count'].values)
gpu_counts = np.log(df['gpu_trans_count'].values)

data = Data([Box(y=counts), Box(y=gpu_counts)])
plot_url = py.plot(data, filename='moore-law-scatter')
print(plot_url)
コード例 #54
0
 def _sign_in():
     py.sign_in('Andrew.Hearst75', 'd5R5jd7z5BqSCot4ClrL')
コード例 #55
0
# If you're using unicode in your file, you may need to specify the encoding.
# You can reproduce this figure in Python with the following code!

# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

import plotly.plotly as py
from plotly.graph_objs import *
import pandas as pd
import numpy as np


#read csv
df = pd.read_csv('cars-sample.csv')

py.sign_in('rtm5151', 'BBtyby2FugITT2qYi7hp')

def getTrace(mfg_name,mfg_color):
    x=df['Weight'][df['Manufacturer'] == mfg_name]
    y=df['MPG'][df['Manufacturer'] == mfg_name]
    size=x
    mfg=df['Manufacturer'][df['Manufacturer'] == mfg_name]
    
    trace = {
      "x": x, 
      "y": y, 
      "marker": {
        "color": mfg_color, 
        "size": size,  
        "sizemode": "area", 
        "sizeref": 24.53, 
コード例 #56
0
def plot_and_tables(excelfile,indexsheet):
    import xlrd
    import pandas as pd
    import plotly.plotly as py
    import plotly.graph_objs as pl
    xls = pd.ExcelFile(excelfile)
    book = xlrd.open_workbook(excelfile)
    this_sheet = book.sheet_by_index(indexsheet)
    nrows = int(this_sheet.cell(3, 2).value)
    ncols = int(this_sheet.cell(4, 2).value)
    indexopt = int(this_sheet.cell(7, 0).value)
    incluir_total_footer = int(this_sheet.cell(3, 9).value)
    type_graph_ind = list()
    trace_colors = list()
    for ii in range(1, ncols+1):
        type_graph_ind.append(int(this_sheet.cell(7, ii).value))
        trace_colors.append(this_sheet.cell(8, ii).value)
    titulo = this_sheet.cell(2, 2).value
    descripcion = this_sheet.cell(5,1).value
    typeofgraph = int(this_sheet.cell(6, 2).value)
    if this_sheet.cell(3, 6).value =="a":
        maxvalue ="a"
        minvalue ="a"
    else:
        maxvalue = int(this_sheet.cell(3, 6).value)
        minvalue = int(this_sheet.cell(4, 6).value)
    if indexopt==0:
        data = xls.parse(indexsheet, skiprows=9,parse_cols=ncols, na_values=['NA'])
    else:
        # index_col=["none"]
        data = xls.parse(indexsheet, skiprows=9, parse_cols=ncols, na_values=['NA'])
    print(nrows)
    df = data[:nrows]
    print(df.head())

    print('Llamando bibliotecas')
    #Plot with plotly
    py.sign_in("glezma", "0q6w6pozu7")
    print('Hecho!!')
    print('Procesando graficos')
    listdata = list()
    for count in range(1,ncols+1):
        print(type_graph_ind[count-1])
        print(type_graph_ind)
        if type_graph_ind[count-1]==0:
            df.head()
            plot = pl.Scatter(x=df['Fecha'], y=df.ix[:,count], mode='lines+markers', marker=pl.Marker(size=8), name=df.columns[int(count)])
            listdata.append(plot)
            print(count)
            layout = pl.Layout()
        elif type_graph_ind[count-1]==1:
            df.head()
            print(df['Fecha'])
            if df.ix[:,count].iloc[-1]>=0:
                plot = pl.Bar(x=df['Fecha'], y=df.ix[:,count], name=df.columns[int(count)],yaxis='y1', marker=pl.Marker(
        color=trace_colors[int(count-1)] )  )
            else:
                plot = pl.Bar(x=df['Fecha'], y=df.ix[:,count], name=df.columns[int(count)],yaxis='y2',marker=pl.Marker(
        color=trace_colors[int(count-1)] ))
            listdata.append(plot)
            print(count)
        else:
            plot = pl.Scatter(x=df['Fecha'], y=df.ix[:,count], mode='lines+markers', marker=pl.Marker(size=8, color='rgba(0, 0, 0, 0.95)'), name=df.columns[int(count)],yaxis='y2')
            listdata.append(plot)
            print(count)
            layout = pl.Layout()
        if minvalue!="a":
            layout = pl.Layout(barmode='stack',bargap=0.6,yaxis=pl.YAxis(title='yaxis title',range=[minvalue, maxvalue]),
                               yaxis2=pl.YAxis(title='yaxis title',side='right',overlaying='y',
                                               tickfont=pl.Font(color='rgb(1, 1, 1)'),range=[minvalue, maxvalue]))
        else:
            layout = pl.Layout()
            #layout = pl.Layout(barmode='stack',yaxis=pl.YAxis(title='yaxis title'),yaxis2=pl.YAxis(title='yaxis title',side='right',overlaying='y'))
    print('Hecho!!')
    pdata = pl.Data(listdata)
    fig = pl.Figure(data=pdata, layout=layout)
    print('Intentando conexion remota...')
    plot_url = py.plot(fig, filename='Repjs_'+ str(indexsheet), auto_open=False)
    plot_url = plot_url + '.embed'
    # plot_url = 'https://plot.ly/~glezma/271.embed'

    df1=df.set_index('Fecha').T
    summary_table = df1 .to_html()    .replace('<table border="1" class="dataframe">', '<table class="display", align = "center", style="width:100%;">')  # use bootstrap styling
    summary_table = summary_table    .replace('<tr style="text-align: right;">', '<tr>')  # use bootstrap styling
    if incluir_total_footer != 0:
        lastindex = df1.index.values[-1]
        toreplace = '''<tr>\n      <th>''' + lastindex
        toplace = '<tfoot>\n <tr>\n      <th>' + lastindex
        summary_table = summary_table    .replace(toreplace, toplace)  # use bootstrap styling
        toreplace ='</tbody>'
        toplace ='</tfoot></tbody>'
        summary_table = summary_table    .replace(toreplace, toplace)
    return (summary_table, plot_url, titulo ,descripcion)
print 'maximum correlation between PC1 and nino: ', maxi
print 'at lag of nino: ', maxlag

maxlag, maxi = highestcorlag(pc2, nino)

print 'maximum correlation between PC2 and nino: ', maxi
print 'at lag of nino: ', maxlag

print 'variance of the different components: ', pca.explained_variance_ratio_

#%% plot in plotly subplot with EOF and PC2
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.tools as tls
"""Sign into Plotly"""
py.sign_in()

trace2 = go.Scatter(x=time,
                    y=pc2,
                    line=dict(width=3, color=('rgb(24,12,255)')),
                    name='second PC')

trace1 = {
    'z':
    eof[:, :, 1],
    'x':
    lon,
    'y':
    lat,
    'type':
    'contour',
コード例 #58
0
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 19 01:40:03 2014

@author: fl@c@
"""
import matplotlib.pyplot as plt
import serial
import numpy as np
import os
import plotly.plotly as py

from plotly.graph_objs import *
py.sign_in("YOUR_USER_ID", "YOUR_USER_KEY")
trace1 = Scatter(x=[1, 2, 3, 4], y=[10, 15, 13, 17])
trace2 = Scatter(x=[1, 2, 3, 4], y=[16, 5, 11, 9])
data = Data([trace1, trace2])
plot_url = py.plot(data, filename='basic-line')


def killOldData():
    try:
        os.remove("spectra.dat")  # remove any previous version of spectra.dat
    except OSError:
        print("   ***   Could not find or delete previous spectra.dat")
        pass


fname = 'spectra.dat'  # set the file name to spectra.dat
fmode = 'ab'  # set the file mode to append binary
lines = 0
コード例 #59
0
ファイル: append.py プロジェクト: VukDukic/documentation
# Learn about API authentication here: {{BASE_URL}}/python/getting-started
# Find your api_key here: {{BASE_URL}}/settings/api

import plotly.plotly as py
from plotly.graph_objs import *

py.sign_in('TestBot', 'r1neazxo9w')
trace1 = Scatter(x=[1, 2, 3, 4], y=[10, 15, 13, 17])
trace2 = Scatter(x=[1, 2, 3, 4], y=[16, 5, 11, 9])
data = Data([trace1, trace2])
plot_url = py.plot(data, filename='append', auto_open=False)
コード例 #60
0
import re
import multiprocessing
import pickle as pkl
import linecache
import pandas as pd
import numpy as np
import random
from commands import getoutput
import itertools
import seaborn as sns
from matplotlib import pyplot as plt
from time import time
import plotly
import plotly.plotly as ptl
from plotly import graph_objs as go
ptl.sign_in('lthiberiol', 'm15ikp59lt')

ncbi = ete3.NCBITaxa()

os.chdir('/work/Alphas_and_Cyanos')
named_reference_tree = ete3.Tree(
    'rooted_partitions-with_named_branches.treefile', format=1)


class cd:
    """  
    Context manager for changing the current working directory
    """
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)