def catCount():
    jobs = pd.read_csv(
        r'C:\Users\lilyk\Desktop\Capstone_project-master\output.csv')
    cat = jobs['category']
    count = (cat.value_counts())
    a = [
        'Artificial Inetlligence', 'Software Engineer', 'Deep Learning',
        'Machine Learning'
    ]
    t = []
    t.append(count['Artificial Intelligence'])
    t.append(count['Software Engineer'])
    t.append(count['Deep Learning'])
    t.append(count['Machine Learning'])

    fig2 = px.bar(jobs,
                  x=a,
                  y=t,
                  color=a,
                  labels={
                      'y': 'Frequency',
                      'x': 'Category'
                  },
                  title=' Frequency of Job Categories')
    fig2.show()

    #This puts it in your cloud for your Chart Studios Account
    #You can switch it to be your account/api_key from your account.
    tls.set_credentials_file(username='******',
                             api_key='3ztc7kdqWPHtPtkhusiy')

    url = py.plot(fig2, filename='categoryFig', auto_open=True)

    return (tls.get_embed(url))
Esempio n. 2
0
def main():
    load_dotenv()
    vk_service_key = os.getenv('VK_SERVICE_KEY')

    parser = argparse.ArgumentParser(
        description='This script get all mentions by keyword in vk.com \
                     count its and visualize with plotly bar chart.'
    )
    parser.add_argument('keyword', help='Input keyword for search')
    parser.add_argument(
        '-d',
        '--days_period',
        default= 7,
        type=int,
        help='Enter days count to search starting today'
    )
    args = parser.parse_args()

    days_period = args.days_period
    timestamps_for_days_period = get_utc_timestamps_for_days_period(
        days_period,
        convert_to_utc_timestamp
    )

    keyword = args.keyword
    max_count = 10
    mentions_by_days = get_mentions_by_days(
        timestamps_for_days_period,
        vk_service_key,
        keyword,
        max_count
    )

    plotly_api_key = os.getenv('PLOTLY_API_KEY')
    plotly_username = os.getenv('PLOTLY_USERNAME')
    chart_studio_tools.set_credentials_file(
        username=plotly_username,
        api_key=plotly_api_key
    )

    days = [mentions_by_day['day'] for mentions_by_day in mentions_by_days]
    mentions_count = [mentions_by_day['count'] for mentions_by_day in mentions_by_days]

    mentions_by_days_bar_chart = go.Figure([go.Bar(x=days, y=mentions_count)])

    chart_url = py.plot(
        mentions_by_days_bar_chart ,
        filename = '{} in vk mentions chart'.format(keyword),
        auto_open=True
    )
    print(chart_url)
Esempio n. 3
0
def plotly_url(data,user, freq='D'):
    """
    Takes list of dicts from django model.objects.values iterable and
    turns it into a dataframe for use with plotly plotting.
    :param data: list containing all values
    :param freq: timeperiod, default H:hour
    :type data: list
    :type freq: str
    """
    try:
        user_plotly = os.environ.get('PLOTLY_USER')
        api = os.environ.get('PLOTLY_API')
        assert len(api) > 0
        assert len(user_plotly) > 0

        # Make dataframe and group by month
        df = pd.DataFrame(data)
        df['created_at'] = pd.to_datetime(df['created_at'])
        if 'user_id' in df.columns: 
            df.rename(columns={'user_id':'user'})
            df['user'] = user

        # Set's up series for plotting by grouping datetime
        df_u = df.groupby(['user','sentiment',pd.Grouper(key='created_at',freq=freq)])['sentiment'].count().reset_index(name='total')
        
        # Get rolling avgs
        df_u['nroll_7'] = df_u[df_u['sentiment']=='Negative'].total.rolling(7,win_type='triang').mean()
        df_u['proll_7'] = df_u[df_u['sentiment']=='Positive'].total.rolling(7,win_type='triang').mean()

        df_u['nroll_7'] = df_u['nroll_7'].fillna(method='bfill').fillna(method='ffill')
        df_u['proll_7'] = df_u['proll_7'].fillna(method='bfill').fillna(method='ffill')

        # Plotly
        tls.set_credentials_file(username=user_plotly,api_key=api)

        user_bar = px.bar(df_u, x="created_at", y="total", color="sentiment",barmode="group", category_orders=co,labels={'created_at':'Date','total':'Total'}, title=f'{user}: Tweets',hover_data=df_u.columns)

        # Plot rolling averages
        user_bar.add_trace(go.Scatter(x=df_u[df_u['sentiment']=='Negative']['created_at'],y=df_u[df_u['sentiment']=='Negative']['nroll_7'], name='nroll_7'))
        user_bar.add_trace(go.Scatter(x=df_u[df_u['sentiment']=='Positive']['created_at'],y=df_u[df_u['sentiment']=='Positive']['proll_7'], name='proll_7'))

        url = py.plot(user_bar, filename=f'{user}_tweets_{freq}',auto_open=False)
        time.sleep(5)
        

        return tls.get_embed(url)

    except Exception as e:
        logger.error(f'plotly_url error: {e}')
def salaries():
    jobs = pd.read_csv(
        r'C:\Users\lilyk\Desktop\Capstone_project-master\output.csv')

    salary = jobs['salary'].dropna()
    category = jobs['category'].dropna().head(200)
    salary = np.array(salary)
    titles = jobs['jobTitle'].dropna().head(200)
    sals = []
    for i in range(len(salary)):

        test = (salary[i].split())
        nums = []

        for i in test:
            if i.startswith('$'):

                number = (i.strip('$'))
                number = number.replace(",", '')
                number = float(number)
                nums.append(number)
            else:
                sals.append(0.0)

        sals.append(statistics.mean(nums))

    fig3 = px.bar(jobs,
                  x=category,
                  y=sals,
                  color=sals,
                  labels={
                      'y': 'Salaries',
                      'x': 'Category'
                  },
                  title='Salaries for Different Job Categories',
                  height=400)

    tls.set_credentials_file(username='******',
                             api_key='3ztc7kdqWPHtPtkhusiy')

    url = py.plot(fig3, filename='salFig', auto_open=True)

    return (tls.get_embed(url))
def edus():
    jobs = pd.read_csv(
        r'C:\Users\lilyk\Desktop\Capstone_project-master\output.csv')

    edus = (jobs['education'].dropna())
    edus = edus.str.split(',')

    #GETS THE UNIQUE EDUS
    u = []
    for x in edus:
        for i in x:
            i = i.replace('bachelors', "bachelor's")
            u.append(i)
    countDict = (Counter(u))
    vals = countDict.values()
    keys = countDict.keys()

    keys, values = zip(*countDict.items())

    fig = px.bar(jobs,
                 x=keys,
                 y=values,
                 color=keys,
                 labels={
                     'y': 'Frequency',
                     'x': 'Education'
                 },
                 title='Most Desired Education Levels')
    #fig.show()

    #This puts it in your cloud for your Chart Studios Account
    #You can switch it to be your account/api_key from your account.
    tls.set_credentials_file(username='******',
                             api_key='3ztc7kdqWPHtPtkhusiy')

    url = py.plot(fig, filename='eduFig', auto_open=True)

    return (tls.get_embed(url))
Esempio n. 6
0
    def map(self, Model):
        username = '******'
        api_key = 'OmWwvBMIO3rYLry5fn5F'
        tls.set_credentials_file(username=username, api_key=api_key)

        states = [
            'al', 'ak', 'az', 'ar', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga',
            'hi', 'id', 'il', 'in', 'ia', 'ks', 'ky', 'la', 'me', 'md', 'ma',
            'mi', 'mn', 'ms', 'mo', 'mt', 'ne', 'nv', 'nh', 'nj', 'nm', 'ny',
            'nc', 'nd', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx',
            'ut', 'vt', 'va', 'wa', 'wv', 'wi', 'wy'
        ]
        locations = [state.upper() for state in states]

        df = self.df.copy()
        df = df.loc[df.index.repeat(len(states))].reset_index(drop=True)
        df['state'] = states
        preds = Model.model.predict(df)
        predictions = [int(pred) for pred in preds]

        fig = go.Figure(data=go.Choropleth(
            locations=locations,  # Spatial coordinates
            z=predictions,  # Data to be color-coded
            locationmode=
            'USA-states',  # set of locations match entries in `locations`
            colorscale='PRGn',
            colorbar_title="Thousands USD",
        ))

        fig.update_layout(
            title_text=
            f'Used {self.titleName()} in {self.condition.capitalize()} Condition Prices by State',
            geo_scope='usa',  # limite map scope to USA
        )

        return py.plot(fig, filename='usedCars_map', auto_open=False)
Esempio n. 7
0
                        size_max=100, zoom=4, 
                        hover_data=['Combined_Key', 'Deaths', 'Population'], 
                        width=1800, height=1000)

fig.show()

import plotly
plotly.__version__

import chart_studio.plotly as py
import chart_studio.tools as tls

usrname = 'ryanzy'
key = 'Mh539mReURbPeNqyub42'

tls.set_credentials_file(username=usrname, api_key=key)

py.plot(fig, filename='fig1', auto_open=False)

pip install geopandas==0.3.0

pip install pyshp==1.2.10

pip install shapely==1.6.3

pip install plotly-geo

import colorlover as cl
from IPython.display import HTML
HTML(cl.to_html( cl.flipper()['seq']['3'] ))
def edu_sal():
    jobs = pd.read_csv(
        r'C:\Users\lilyk\Desktop\Capstone_project-master\output.csv')
    #makes it so u can graph, but messes up data
    edus = (jobs['education'].fillna('Not Specified').head(235))
    edus = edus.str.split(',')

    #GETS THE UNIQUE EDUS
    u = []
    for x in edus:
        for i in x:
            i = i.replace('bachelors', "bachelor's")
            u.append(i)
    print(len(u))

    #keys,values = zip(*countDict.items())
    ##KEYS IS EDUS

    salary = jobs['salary'].dropna()

    salary = np.array(salary)

    sals = []
    for i in range(len(salary)):

        # print (salary[i])
        test = (salary[i].split())
        nums = []

        for i in test:
            if i.startswith('$'):

                number = (i.strip('$'))
                number = number.replace(",", '')
                #print (number)
                number = float(number)
                #print (number)
                nums.append(number)
            else:
                pass

            try:
                sals.append(statistics.mean(nums))
            except:
                sals.append(nums)

    #print (sals)
    print(len(sals))

    fig = px.scatter(jobs,
                     x=u,
                     y=sals,
                     color=u,
                     labels={
                         'y': 'Sal',
                         'x': 'Education'
                     },
                     title='edu/sal',
                     size=sals)

    tls.set_credentials_file(username='******',
                             api_key='3ztc7kdqWPHtPtkhusiy')

    url = py.plot(fig, filename='scatEduSal', auto_open=True)

    return (tls.get_embed(url))
Esempio n. 9
0
def plot_karma_metric(allVotes,
                      start_date,
                      end_date,
                      online=False,
                      period='D',
                      ma=7):
    votes_ts = allVotes.set_index('votedAt').resample(period)['effect'].sum()
    votes_ts = votes_ts.reset_index().iloc[:-1]
    votes_ts_ma = votes_ts.set_index('votedAt')['effect'].rolling(
        ma).mean().round(1).reset_index()

    days_in_period = {'D': 1, 'W': 7, 'M': 365 / 12, 'Y': 365}

    # trends = create_trend_frame(days_in_period[period] * 550, period)

    # plotly section
    date_col = 'votedAt'
    title = 'effect'
    color = 'red'
    size = (1200, 500)

    data = [
        go.Scatter(x=votes_ts[date_col],
                   y=votes_ts['effect'].round(1),
                   line={
                       'color': color,
                       'width': 0.5
                   },
                   name='{}-value'.format(PERIOD_DICT[period]),
                   hoverinfo='x+y+name'),
        go.Scatter(x=votes_ts_ma[date_col],
                   y=votes_ts_ma['effect'].round(1),
                   line={
                       'color': color,
                       'width': 4
                   },
                   name='average of last {} {}s'.format(
                       ma, PERIOD_DICT2[period]),
                   hoverinfo='x+y+name')  #,
        # go.Scatter(x=trends['date'], y=trends['5%'], line={'color': 'grey', 'width': 1, 'dash': 'dash'}, mode='lines',
        #            name='5% growth', hoverinfo='skip'),
        # go.Scatter(x=trends['date'], y=trends['7%'], line={'color': 'black', 'width': 2, 'dash': 'dash'}, mode='lines',
        #            name='7% growth', hoverinfo='x+y'),
        # go.Scatter(x=trends['date'], y=trends['10%'], line={'color': 'grey', 'width': 1, 'dash': 'dash'}, mode='lines',
        #            name='10% growth', hoverinfo='skip')
    ]

    layout = go.Layout(
        autosize=True,
        width=size[0],
        height=size[1],
        title='Net Karma, 4x Downvote, {}, 1.2 item exponent'.format(
            PERIOD_DICT[period].capitalize()),
        xaxis={
            'range': [start_date, end_date],
            'title': None
        },
        yaxis={
            'range': [
                0,
                votes_ts.set_index(date_col)[start_date:]['effect'].max() * 1.1
            ],
            'title':
            'net karma'
        })

    fig = go.Figure(data=data, layout=layout)

    set_credentials_file(username=get_config_field('PLOTLY', 'username'),
                         api_key=get_config_field('PLOTLY', 'api_key'))
    init_notebook_mode(connected=True)

    filename = 'Net Karma Metric - {}'.format(PERIOD_DICT[period].capitalize())
    if online:
        py.iplot(fig, filename=filename)
    else:
        iplot(fig, filename=filename)

    return votes_ts
Esempio n. 10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import numpy as np
import pandas as pd
#import plotly.tools as tls
import chart_studio.tools as tls
#import plotly.plotly as py
import chart_studio.plotly as py
import plotly.graph_objs as go

tls.set_credentials_file(username='******', api_key='?????')

listeDef = ['FULL', 'N0', 'S0']
listeFeuille = ['F3', 'F5']
minDas = 23


def organizeData(mat):
    """
    fonction qui transforme les données en dictionnaire
    :param mat: les données importées du csv
    :return: les données sous forme dictionnaire
    """
    print("\\\\\\\\\\\  Transform data to dict  ////////////")
    data = []
    for line in mat:
        dico = {
            'Sample': line[0],
            'Moda': line[1],
            'Feuille': line[2],
Esempio n. 11
0
import plotly
import chart_studio.tools as plt_tools
plt_tools.set_credentials_file(username="******", api_key="vEU6zehnSVEJ3oA8WqWA")

import chart_studio.plotly as py

import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import plotly.express as px
import sys
import argparse


def parseArgs(args):
    """
    Wrapper function to parse script arguments
    :param args: script arguments
    :return: args: parsed arguments object
    """

    parser = argparse.ArgumentParser(
        description="This script performs plotly plot generation.")

    parser.add_argument(
        "--input_csvs",
        "-ic",
        nargs='+',
        type=str,
        dest="input_csvs",
        default=[
"""Plotly chart creation."""
import plotly.graph_objects as go
import chart_studio.plotly as py
from chart_studio.tools import set_credentials_file
from pandas import DataFrame
from config import PLOTLY_API_KEY, PLOTLY_USERNAME

# Plotly Chart Studio authentication
set_credentials_file(
    username=PLOTLY_USERNAME,
    api_key=PLOTLY_API_KEY
)


def create_chart(stock_df: DataFrame, symbol: str) -> py.plot:
    """Create Plotly chart from Pandas DataFrame."""
    fig = go.Figure(data=[
        go.Candlestick(
            x=stock_df.index,
            open=stock_df['open'],
            high=stock_df['high'],
            low=stock_df['low'],
            close=stock_df['close'],
            decreasing={
                "line": {
                    "color": "rgb(240, 99, 90)"
                },
                "fillcolor": "rgba(142, 53, 47, 0.5)"
            },
            increasing={
                "line": {
Esempio n. 13
0
    def __init__(self, length=3, distance=0, seed=None):
        '''
		Arguments: 
		size (int): Determines the length of all cube faces. Ie, each face
		will have size^2 many squares.

		distance (int): The number of random moves used to generate the cube's 
		starting position. 

		seed (int): Optional argument that can be used to fix the random moves
		used to generate the position. When distance and seed are fixed, the same
		starting position will be generated. 
		'''

        self.face_colors = {
            'front': 'yellow',
            'right': 'red',
            'back': 'green',
            'left': 'orange',
            'top': 'blue',
            'bottom': 'white'
        }
        self.faces = list(self.face_colors.keys())
        self.face_area = length**2
        num_faces = 6
        self.num_squares = num_faces * self.face_area
        self.face_indices = {self.faces[i]: i for i in range(num_faces)}
        self.color_labels = {
            color: color[0]
            for color in self.face_colors.values()
        }
        self.label_colors = {
            label: color
            for color, label in self.color_labels.items()
        }
        self.grid = list(
            itertools.product(np.arange(length), np.arange(length)))
        self.faces = np.array([[[
            self.color_labels[self.face_colors[face]] for i in range(length)
        ] for j in range(length)] for face in self.face_colors])

        self.front, self.right, self.back, self.left, self.top, self.bottom = self.faces[
            0:6, :, :]
        self.invert = lambda index: abs(2 - index)
        self.face_radius = 0.5
        directions, dims, layers = [True, False], range(length), range(length)
        self.moves = list(itertools.product(dims, layers, directions))

        # The None move entails doing nothing. It's included so that the search
        # algorithm isn't limited to finding solutions of the given search depth.
        self.moves.insert(0, None)
        self.compressions = []
        self.face_to_axis = {
            'front': 1,
            'back': 1,
            'left': 0,
            'right': 0,
            'top': 2,
            'bottom': 2
        }
        self.reward_hist = {}
        self.prev_moves = []
        self.tried_moves = defaultdict(set)
        self.move_history = []

        self.build_face_to_cartestian()
        self.x_dom = np.linspace(-3, 6, 10)
        self.y_dom = np.linspace(-3, 6, 10)
        self.z_dom = np.linspace(-3, 6, 10)
        self.input_faces = {
            'xy': {
                True: [3, 0, 1, 2],
                False: [1, 2, 3, 0]
            },
            'xz': {
                True: [5, 0, 4, 2],
                False: [4, 2, 5, 0]
            }
        }
        self.output_faces = {'xy': range(4), 'xz': [0, 4, 2, 5]}
        self.input_cols = {
            'xz': {
                True:
                lambda col: [col, col, col, self.invert(col)],
                False:
                lambda col: [self.invert(col),
                             self.invert(col), col, col]
            }
        }
        self.output_cols = {
            'xz': {
                True: lambda col: [col, col, self.invert(col), col],
                False:
                lambda col: [col, self.invert(col),
                             self.invert(col), col]
            }
        }
        self.flip_faces = {
            'xz': {
                True: lambda col: [col, self.invert(col)],
                False: lambda col: [self.invert(col), col]
            }
        }
        self.flip_cols = {
            'xz': {
                True: lambda col: [col, self.invert(col)],
                False: lambda col: [self.invert(col), col]
            }
        }
        self.rotations = {
            tuple([0, 0, True]): ['top', -1],
            tuple([0, 0, False]): ['top', 1],
            tuple([0, 2, True]): ['bottom', -1],
            tuple([0, 2, False]): ['bottom', 1],
            tuple([1, 0, True]): ['left', 1],
            tuple([1, 0, False]): ['left', -1],
            tuple([1, 2, True]): ['right', -1],
            tuple([1, 2, False]): ['right', 1],
            tuple([2, 0, True]): ['front', 1],
            tuple([2, 0, False]): ['front', -1],
            tuple([2, 2, True]): ['back', -1],
            tuple([2, 2, False]): ['back', 1]
        }

        self.random_position(distance, seed)
        api_key = "MuCqsAcD75SBG4BSEuQx"
        tools.set_credentials_file(username='******', api_key=api_key)
Esempio n. 14
0
import os
from bottle import run, template, get, post, request
from chart_studio.plotly import plot
from chart_studio import tools
from plotly.graph_objects import Bar

tools.set_credentials_file(username='******', api_key='ECoh0rzizfQ8eUpUolkx')

index_html = '''My first web app! By <strong>{{ author }}</strong>.'''


@get('/plot')
def form():
    return '''<h2>Graph via Plot.ly</h2>
              <form method="POST" action="/plot">
                Name: <input name="name1" type="text" />
                Age: <input name="age1" type="text" /><br/>
                Name: <input name="name2" type="text" />
                Age: <input name="age2" type="text" /><br/>
                Name: <input name="name3" type="text" />
                Age: <input name="age3" type="text" /><br/>
                <input type="submit" />
              </form>'''


@post('/plot')
def submit():
    # grab data from form
    name1 = request.forms.get('name1')
    age1 = request.forms.get('age1')
    name2 = request.forms.get('name2')
Esempio n. 15
0
import os

import plotly.graph_objects as go
import chart_studio.tools as chst_tl
import chart_studio.plotly as chst_pl
from dotenv import load_dotenv

# import visualizer
import data

# user = visualizer.GithubUser()

load_dotenv()
chst_tl.set_credentials_file(username=os.getenv("CHART_STUDIO_USERNAME"),
                             api_key=os.getenv("CHART_STUDIO_APIKEY"))


class IndexPlot():
    def __init__(self):
        pass

    def plot_k(self, group, index, period):

        # extract data
        if (group == "us_indexes"):
            holder = data.IndexDataHolder(
                "../finance_data/{group}/{id}.csv".format(group=group,
                                                          id=index))
        elif (group == "us_stocks"):
            holder = data.StockDataHolder(
                "../finance_data/{group}/{id}.csv".format(group=group,
Esempio n. 16
0
import numpy as np
import pandas as pd

import chart_studio.plotly as py
import chart_studio.tools as tls

# credientials to access plotly map
tls.set_credentials_file(username='******', api_key='9NS3Rm5M37XgJXMP1boe')

# grab data from CDC covid data
address = 'C:\\Users\\dejat\\OneDrive\\Documents\\covidthing.csv'
states = pd.read_csv(address)
states.columns = ['state', 'cases']
states.head()

states['text'] = 'cases' + states['cases'].astype(str)

data = [
    dict(type='choropleth',
         autocolorscale=False,
         locations=states['state'],
         z=states['cases'],
         locationmode='USA-states',
         text=states['text'],
         colorscale='emrld',
         colorbar=dict(title="Number of cases"))
]

layout = dict(
    title="Covid cases in USA",
    geo=dict(
meta_info = {"chart_name":"Consumer Price Index for All Urban Consumers","x_axis":"Date", "y_axis":"CPI", "series_id":"CPIAUCSL", "observation_start":"1995-01-01", "observation_end":FRED_date}
try:
	fred = Fred(fred_api_key) # Login.
	data = fred.get_series(series_id=meta_info["series_id"], observation_start=meta_info["observation_start"], observation_end=meta_info["observation_end"])
	meta_info["data"] = format_series(data, meta_info)
	charts.append(meta_info)
	print_and_pause('Saved', meta_info["chart_name"])
except:
	cleanup(f"Error retreiving and/or parsing series: {meta_info['chart_name']}.")


#################### SHIP DATA ####################

# Log into the Plotly account.
try:
	tls.set_credentials_file(plotly_username, plotly_api_key)
	print_and_pause("Logging into", "Plotly API")
except:
	cleanup("Error logging into plotly.")

# Submit each item to plotly cloud.
for item in charts:
	df = item["data"]
	fig = px.line(df, x=item['x_axis'], y=item["y_axis"], title=item["chart_name"]) # Plot item.
	py.plot(fig, filename=item["chart_name"], auto_open=False) # Ship item off to the Plotly API.
	print_and_pause('Shipped', item["chart_name"])

# Confirmation of completion.
if run_without_errors:
	cleanup("Done")
Esempio n. 18
0
def run_plotline(dfs,
                 online=False,
                 start_date=None,
                 end_date=None,
                 size=(1000, 400),
                 pr='D',
                 ma=[1, 7],
                 widths={
                     1: 0.75,
                     7: 3
                 },
                 annotations=False,
                 hidden_by_default=[]):
    set_credentials_file(username=get_config_field('PLOTLY', 'username'),
                         api_key=get_config_field('PLOTLY', 'api_key'))
    init_notebook_mode(connected=True)

    dpv = dfs['views']  # pv = post-views

    minimum_post_views = 1
    valid_users = get_valid_users(
        dfs, required_minimum_posts_views=minimum_post_views)
    valid_posts = get_valid_posts(dfs, required_upvotes=1)
    valid_comments = get_valid_comments(dfs)
    valid_votes = get_valid_votes(dfs)
    valid_views = get_valid_views(dfs)
    valid_views['hour'] = valid_views['createdAt'].dt.round('H')
    valid_views_deduped = valid_views.drop_duplicates(
        subset=['userId', 'documentId', 'hour'])

    plotly_args = {
        'start_date': start_date,
        'end_date': end_date,
        'period': pr,
        'moving_average_lengths': ma,
        'widths': widths,
        'size': size,
        'online': online,
        'annotations': annotations,
        'hidden_by_default': hidden_by_default
    }

    timeseries_plot(
        title='Accounts Created, {}+ posts_viewed'.format(minimum_post_views),
        datapoints=valid_users,
        date_col='true_earliest',
        color='grey',
        **plotly_args)
    timeseries_plot(title='Num Logged-In Users',
                    datapoints=dpv[dpv['userId'].isin(valid_users['_id'])],
                    date_col='createdAt',
                    color='black',
                    unique_on='userId',
                    **plotly_args)

    timeseries_plot(title='Num Posts with 2+ upvotes',
                    datapoints=valid_posts,
                    date_col='postedAt',
                    color='blue',
                    **plotly_args)
    timeseries_plot(title='Num Unique Posters',
                    datapoints=valid_posts,
                    date_col='postedAt',
                    color='darkblue',
                    unique_on='userId',
                    **plotly_args)

    timeseries_plot(title='Num Comments',
                    datapoints=valid_comments,
                    date_col='postedAt',
                    color='green',
                    **plotly_args)
    timeseries_plot(title='Num Unique Commenters',
                    datapoints=valid_comments,
                    date_col='postedAt',
                    color='darkgreen',
                    unique_on='userId',
                    **plotly_args)

    timeseries_plot(title='Num Votes (excluding self-votes)',
                    datapoints=valid_votes,
                    date_col='votedAt',
                    color='orange',
                    **plotly_args)
    timeseries_plot(title='Num Unique Voters',
                    datapoints=valid_votes,
                    date_col='votedAt',
                    color='darkorange',
                    unique_on='userId',
                    **plotly_args)

    timeseries_plot(title='Num Logged-In Post Views',
                    datapoints=valid_views_deduped,
                    date_col='createdAt',
                    color='red',
                    **plotly_args)
# In[ ]:

from google.colab import files  # Para manejar los archivos y, por ejemplo, exportar a su navegador
import glob  # Para manejar los archivos y, por ejemplo, exportar a su navegador
from google.colab import drive  # Montar tu Google drive

# # Gráficos con PlotLy

# In[1]:

get_ipython().system('pip install chart_studio')
import chart_studio.plotly as py
import plotly.graph_objects as go
from chart_studio import tools as tls

tls.set_credentials_file(username='******',
                         api_key='6mEfSXf8XNyIzpxwb8z7')

# In[2]:

import plotly
plotly.__version__

# In[5]:

help(plotly)

# In[8]:

import numpy as np
help(np.random)
Esempio n. 20
0
                " States with Largest Increase from 1996 to 2019",
                xticks=range(0, len(df_yearAgg)))
plt.legend(title="State", bbox_to_anchor=(1, 1))
plt.xticks(rotation=90)
plt.grid(True)
plt.xlabel('By Year')
plt.ylabel('Average Price, in thousands')
plt.show()

# US states heatmap
import chart_studio.plotly as py
import chart_studio.tools as tls

df_rise_stateAgg.reset_index(level=0, inplace=True)

tls.set_credentials_file(username='******', api_key='RsKQETjmHeHXwG8oM71w')

df_rise_stateAgg[
    'Text'] = ''  #'States' + df_rise_stateAgg['State'] + '<br>' + 'Average Price' + df_rise_stateAgg['2019-05'].astype(str)

data = [dict(type = 'choropleth', autocolorscale = False, locations = df_rise_stateAgg['State'], z = df_rise_stateAgg['2019-06'],\
             locationmode = 'USA-states', text = df_rise_stateAgg['Text'], colorscale = 'Portland',\
             colorbar = dict(title = 'Average Housing Price'))]

layout = dict(
    title="2-Bedroom Average Housing Price in June 2019, in thousands",
    geo=dict(scope='usa', projection=dict(type='albers usa')))

fig = dict(data=data, layout=layout)

py.plot(fig, filename="Housing Price")
import os
import numpy as np
import pandas as pd
from tqdm.notebook import tqdm

import plotly.graph_objects as go
import chart_studio.plotly as py
import chart_studio.tools as tls

# Log into Chart studio for visual chart upload

tls.set_credentials_file(username='******', api_key='••••••••')


# Custom function for pretty-printing a number with comma-separators and/or decimal vals
def comma_num(x, dollars=0, dec=0):

    if dec: x = round(x, dec)
    elif dollars: x = round(x)
    minus = False
    x = str(x)
    if '-' in x:
        minus = True
        x = x.replace('-', '').strip()
    parts = [list(l) for l in x.split('.')]
    predec = parts[0]
    if len(parts) > 1: postdec = parts[-1]
    else: postdec = None

    if len(predec) > 3:
        for i in list(range(-3, -len(predec) - 1, -4)):
Esempio n. 22
0
import gspread
import random
import chart_studio.plotly as py
from chart_studio import tools
from datetime import time

# Plotly Credentials
tools.set_credentials_file(username='******', api_key='INSERT_YOURS_HERE')

# updated oauth
from google.oauth2.service_account import Credentials

# Express time in twenty-four hour format
OpenVoteHour = 20 # the hour the poll opens
OpenVoteMin = 50 # the minute the poll opens
CloseVoteHour = 22 # the hour the poll closes
CloseVoteMin = 0 # the minute the poll closes


# Not Sure a better way to Map Human Readable to Code
# Also, zero index ;)
ChoiceMap = {
    u"First Choice": 0,
    u"Second Choice": 1,
    u"Third Choice": 2,
    u"Fourth Choice": 3,
    u"Fifth Choice": 4,
    u"Sixth Choice": 5,
    u"Seventh Choice": 6,
    u"Eighth Choice": 7,
    u"Ninth Choice": 8,