Ejemplo n.º 1
0
def population():
    xdr = FactorRange(factors=years)
    ydr = DataRange1d()
    x_scale = CategoricalScale()

    plot = Plot(x_range=xdr,
                y_range=ydr,
                x_scale=x_scale,
                plot_width=600,
                plot_height=150,
                toolbar_location=None)

    plot.add_layout(CategoricalAxis(major_label_orientation=pi / 4), 'below')

    known = Line(x="x", y="y", line_color="violet", line_width=2)
    known_glyph = plot.add_glyph(source_known, known)

    predicted = Line(x="x",
                     y="y",
                     line_color="violet",
                     line_width=2,
                     line_dash="dashed")
    predicted_glyph = plot.add_glyph(source_predicted, predicted)

    legend = Legend(location="bottom_right",
                    items=[("known", [known_glyph]),
                           ("predicted", [predicted_glyph])])
    plot.add_layout(legend)

    return plot
Ejemplo n.º 2
0
def pyramid():
    xdr = DataRange1d()
    ydr = FactorRange(factors=groups)
    y_scale = CategoricalScale()

    plot = Plot(x_range=xdr,
                y_range=ydr,
                y_scale=y_scale,
                plot_width=600,
                plot_height=500,
                toolbar_location=None)

    xaxis = LinearAxis()
    plot.add_layout(xaxis, 'below')
    plot.add_layout(CategoricalAxis(), 'left')

    plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))

    m = HBar(left="value", right=0, y="group", height=1, fill_color="#3B8686")
    mglyph = plot.add_glyph(source_pyramid_m, m)

    f = HBar(left=0, right="value", y="group", height=1, fill_color="#CFF09E")
    fglyph = plot.add_glyph(source_pyramid_f, f)

    plot.add_layout(Legend(items=[("Male", [mglyph]), ("Female", [fglyph])]))

    return plot
Ejemplo n.º 3
0
    def test_reset_triggers_factorrange_callbacks(self, single_plot_page):
        source = ColumnDataSource(dict(x=["a", "b"], y=["a", "a"]))
        plot = Plot(plot_height=400,
                    plot_width=400,
                    x_scale=CategoricalScale(),
                    x_range=FactorRange(factors=["a", "b", "c"]),
                    y_scale=CategoricalScale(),
                    y_range=FactorRange(factors=["a", "b", "c"]),
                    min_border=0)
        plot.add_glyph(source, Circle(x='x', y='y', size=20))
        plot.add_tools(ResetTool(), ZoomInTool())
        plot.x_range.callback = CustomJS(code=COUNT("xrcb"))
        plot.x_range.js_on_change('start', CustomJS(code=COUNT("xrstart")))
        plot.x_range.js_on_change('end', CustomJS(code=COUNT("xrend")))
        plot.y_range.callback = CustomJS(code=COUNT("yrcb"))
        plot.y_range.js_on_change('start', CustomJS(code=COUNT("yrstart")))
        plot.y_range.js_on_change('end', CustomJS(code=COUNT("yrend")))

        page = single_plot_page(plot)

        # Change the ranges using a zoom in tool
        button = page.get_toolbar_button('zoom-in')
        button.click()

        results = page.results
        assert results['xrcb'] == 1
        assert results['xrstart'] == 1
        assert results['xrend'] == 1
        assert results['yrcb'] == 1
        assert results['yrstart'] == 1
        assert results['yrend'] == 1

        # Click the reset tool and check the callback was called
        button = page.get_toolbar_button('reset')
        button.click()

        results = page.results
        assert results['xrcb'] == 3
        assert results['xrstart'] == 2
        assert results['xrend'] == 2
        assert results['yrcb'] == 3
        assert results['yrstart'] == 2
        assert results['yrend'] == 2

        assert page.has_no_console_errors()
Ejemplo n.º 4
0
def test__check_compatible_scale_and_ranges_incompat_factor_scale_and_numeric_range(
) -> None:
    plot = Plot(x_scale=CategoricalScale(), x_range=DataRange1d())
    check = plot._check_compatible_scale_and_ranges()
    assert check != []
Ejemplo n.º 5
0
def test__check_compatible_scale_and_ranges_compat_factor() -> None:
    plot = Plot(x_scale=CategoricalScale(), x_range=FactorRange())
    check = plot._check_compatible_scale_and_ranges()
    assert check == []
Ejemplo n.º 6
0
for name in groups.__all__:
    group = getattr(groups, name)
    data.extend([(str(x), x.to_hex(), group.__name__) for x in group])

css3_colors = pd.DataFrame(data, columns=["Name", "Color", "Group"])

source = ColumnDataSource(
    dict(
        names=list(css3_colors.Name),
        groups=list(css3_colors.Group),
        colors=list(css3_colors.Color),
    ))

xdr = FactorRange(factors=list(css3_colors.Group.unique()))
ydr = FactorRange(factors=list(reversed(css3_colors.Name)))
x_scale, y_scale = CategoricalScale(), CategoricalScale()

plot = Plot(x_range=xdr,
            y_range=ydr,
            x_scale=x_scale,
            y_scale=y_scale,
            plot_width=600,
            plot_height=2000)
plot.title.text = "CSS3 Color Names"

rect = Rect(x="groups",
            y="names",
            width=1,
            height=1,
            fill_color="colors",
            line_color=None)
Ejemplo n.º 7
0
def make_calendar(year, month, firstweekday="Mon"):
    firstweekday = list(day_abbrs).index(firstweekday)
    calendar = Calendar(firstweekday=firstweekday)

    month_days  = [ None if not day else str(day) for day in calendar.itermonthdays(year, month) ]
    month_weeks = len(month_days)//7

    workday = "linen"
    weekend = "lightsteelblue"

    def weekday(date):
        return (date.weekday() - firstweekday) % 7

    def pick_weekdays(days):
        return [ days[i % 7] for i in range(firstweekday, firstweekday+7) ]

    day_names = pick_weekdays(day_abbrs)
    week_days = pick_weekdays([workday]*5 + [weekend]*2)

    source = ColumnDataSource(data=dict(
        days            = list(day_names)*month_weeks,
        weeks           = sum([ [str(week)]*7 for week in range(month_weeks) ], []),
        month_days      = month_days,
        day_backgrounds = sum([week_days]*month_weeks, []),
    ))

    holidays = [ (date, summary.replace("(US-OPM)", "").strip()) for (date, summary) in us_holidays
        if date.year == year and date.month == month and "(US-OPM)" in summary ]

    holidays_source = ColumnDataSource(data=dict(
        holidays_days  = [ day_names[weekday(date)] for date, _ in holidays ],
        holidays_weeks = [ str((weekday(date.replace(day=1)) + date.day) // 7) for date, _ in holidays ],
        month_holidays = [ summary for _, summary in holidays ],
    ))

    xdr = FactorRange(factors=list(day_names))
    ydr = FactorRange(factors=list(reversed([ str(week) for week in range(month_weeks) ])))
    x_scale, y_scale = CategoricalScale(), CategoricalScale()

    plot = Plot(x_range=xdr, y_range=ydr, x_scale=x_scale, y_scale=y_scale,
                plot_width=300, plot_height=300, outline_line_color=None)
    plot.title.text = month_names[month]
    plot.title.text_font_size = "16px"
    plot.title.text_color = "darkolivegreen"
    plot.title.offset = 25
    plot.min_border_left = 0
    plot.min_border_bottom = 5

    rect = Rect(x="days", y="weeks", width=0.9, height=0.9, fill_color="day_backgrounds", line_color="silver")
    plot.add_glyph(source, rect)

    rect = Rect(x="holidays_days", y="holidays_weeks", width=0.9, height=0.9, fill_color="pink", line_color="indianred")
    rect_renderer = plot.add_glyph(holidays_source, rect)

    text = Text(x="days", y="weeks", text="month_days", text_align="center", text_baseline="middle")
    plot.add_glyph(source, text)

    xaxis = CategoricalAxis()
    xaxis.major_label_text_font_size = "11px"
    xaxis.major_label_standoff = 0
    xaxis.major_tick_line_color = None
    xaxis.axis_line_color = None
    plot.add_layout(xaxis, 'above')

    hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[("Holiday", "@month_holidays")])
    plot.tools.append(hover_tool)

    return plot
Ejemplo n.º 8
-1
def make_calendar(sp500_data_lst,
                  djia_data_lst,
                  nasdaq_data_lst,
                  twitter_data_lst,
                  holiday_lst,
                  nyt_data_lst,
                  approval_data_lst,
                  generic_dem_lst,
                  generic_rep_lst,
                  plot_wid,
                  plot_ht,
                  year,
                  month,
                  firstweekday="Sun"):
    firstweekday = list(day_abbrs).index(firstweekday)
    calendar = Calendar(firstweekday=firstweekday)

    month_days = [
        None if not day else str(day)
        for day in calendar.itermonthdays(year, month)
    ]
    month_weeks = len(month_days) // 7

    workday = "linen"
    weekend = "lightsteelblue"

    def weekday(date):
        return (date.weekday() - firstweekday) % 7

    def pick_weekdays(days):
        return [days[i % 7] for i in range(firstweekday, firstweekday + 7)]

    day_names = pick_weekdays(day_abbrs)
    week_days = pick_weekdays([workday] * 5 + [weekend] * 2)

    source = ColumnDataSource(data=dict(
        days=list(day_names) * month_weeks,
        weeks=sum([[str(week)] * 7 for week in range(month_weeks)], []),
        month_days=month_days,
        day_backgrounds=['white'] * len(month_days),
    ))

    djia_data = [(dj_date, DJIA) for (dj_date, DJIA) in djia_data_lst
                 if dj_date.year == year and dj_date.month == month]

    nasdaq_data = [(nas_date, NASDAQCOM)
                   for (nas_date, NASDAQCOM) in nasdaq_data_lst
                   if nas_date.year == year and nas_date.month == month]

    sp500_data = [(sp500_date, SP500) for (sp500_date, SP500) in sp500_data_lst
                  if sp500_date.year == year and sp500_date.month == month]

    holidays = [(holiday_date, Holiday)
                for (holiday_date, Holiday) in holiday_lst
                if holiday_date.year == year and holiday_date.month == month]

    twitter_data = [
        (twitter_date, topics) for (twitter_date, topics) in twitter_data_lst
        if twitter_date.year == year and twitter_date.month == month
    ]

    nyt_data = [(nyt_date, headlines) for (nyt_date, headlines) in nyt_data_lst
                if nyt_date.year == year and nyt_date.month == month]

    approval_data = [
        (approval_date, approve_estimate)
        for (approval_date, approve_estimate) in approval_data_lst
        if approval_date.year == year and approval_date.month == month
    ]
    approval_data.sort()

    generic_dem = [(generic_date, dem_estimate)
                   for (generic_date, dem_estimate) in generic_dem_lst
                   if generic_date.year == year and generic_date.month == month
                   ]
    generic_dem.sort()

    generic_rep = [(generic_date, rep_estimate)
                   for (generic_date, rep_estimate) in generic_rep_lst
                   if generic_date.year == year and generic_date.month == month
                   ]
    generic_rep.sort()

    colors_djia = [DJIA for _, DJIA in djia_data]
    colors_sp500 = [SP500 for _, SP500 in sp500_data]
    colors_nasdaq = [NASDAQCOM for _, NASDAQCOM in nasdaq_data]

    for i in range(len(colors_djia) - 1):
        avg = np.mean([colors_djia[i], colors_sp500[i], colors_nasdaq[i]])

        if 0 < avg <= 11000:
            colors_djia[i] = '#E52700'
        elif 11000 < avg <= 11100:
            colors_djia[i] = '#E33A00'
        elif 11100 < avg <= 11200:
            colors_djia[i] = '#E14C00'
        elif 11200 < avg <= 11300:
            colors_djia[i] = '#DF5E00'
        elif 11300 < avg <= 11400:
            colors_djia[i] = '#DD6F00'
        elif 11400 < avg <= 11500:
            colors_djia[i] = '#DB8000'
        elif 11500 < avg <= 11600:
            colors_djia[i] = '#D99100'
        elif 11600 < avg <= 11700:
            colors_djia[i] = '#D7A100'
        elif 11700 < avg <= 11800:
            colors_djia[i] = '#D5B100'
        elif 11800 < avg <= 11900:
            colors_djia[i] = '#D3C100'
        elif 11900 < avg <= 12000:
            colors_djia[i] = '#D1D000'
        elif 12000 < avg <= 12100:
            colors_djia[i] = '#BECF00'
        elif 12200 < avg <= 12300:
            colors_djia[i] = '#ABCD00'
        elif 12300 < avg <= 12400:
            colors_djia[i] = '#99CB00'
        elif 12400 < avg <= 12500:
            colors_djia[i] = '#87C900'
        elif 12500 < avg <= 12600:
            colors_djia[i] = '#75C700'
        elif 12500 < avg <= 12600:
            colors_djia[i] = '#64C500'
        else:
            colors_djia[i] = '#53C300'

    holiday_source = ColumnDataSource(data=dict(
        month_djia=[DJIA for _, DJIA in djia_data],
        month_nasdaq=[NASDAQCOM for _, NASDAQCOM in nasdaq_data],
        month_sp500=[SP500 for _, SP500 in sp500_data],
        month_twitter=[topics for _, topics in twitter_data],
        month_holidays=[Holiday for _, Holiday in holidays],
        nyt_days=[day_names[weekday(nyt_date)] for nyt_date, _ in nyt_data],
        nyt_weeks=['0'] + [
            str((weekday(nyt_date.replace(day=1)) + nyt_date.day) // 7)
            for nyt_date, _ in nyt_data
        ],
        month_nyt=[headlines for _, headlines in nyt_data],
        month_approval=[
            approve_estimate for _, approve_estimate in approval_data
        ],
        month_generic_dem=[dem_estimate for _, dem_estimate in generic_dem],
        month_generic_rep=[rep_estimate for _, rep_estimate in generic_rep],
        day_backgrounds=colors_djia,
    ))

    xdr = FactorRange(factors=list(day_names))
    ydr = FactorRange(
        factors=list(reversed([str(week) for week in range(month_weeks)])))
    x_scale, y_scale = CategoricalScale(), CategoricalScale()

    plot = Plot(x_range=xdr,
                y_range=ydr,
                x_scale=x_scale,
                y_scale=y_scale,
                plot_width=plot_wid,
                plot_height=plot_ht)
    plot.title.text = month_names[month] + " " + str(year)
    plot.title.text_font_size = "14pt"
    plot.title.text_color = "black"
    plot.title.offset = 25
    plot.min_border_left = 5
    plot.min_border_top = 5
    plot.min_border_bottom = 190
    plot.border_fill_color = "white"
    plot.background_fill_alpha = 0.5
    plot.border_fill_alpha = 0.3

    rect = Rect(x="days",
                y="weeks",
                width=0.9,
                height=0.9,
                fill_color="day_backgrounds",
                line_color="silver")
    plot.add_glyph(source, rect)

    rect = Rect(x="nyt_days",
                y="nyt_weeks",
                width=0.9,
                fill_color="day_backgrounds",
                height=0.9)
    rect_renderer = plot.add_glyph(holiday_source, rect)

    text = Text(x="days",
                y="weeks",
                text="month_days",
                text_align="center",
                text_baseline="middle")
    plot.add_glyph(source, text)

    xaxis = CategoricalAxis()
    xaxis.major_label_text_font_size = "10pt"
    xaxis.major_label_standoff = 0
    xaxis.major_tick_line_color = None
    xaxis.axis_line_color = None
    plot.add_layout(xaxis, 'above')

    TOOLTIPS = """
	<div style="height:100%; max-width:300px; min-width:200px;background-color: aliceblue; position:relative;">
		<div>
			<span style="font-size: 17px; font-weight: bold;"> Holiday: @month_holidays</span><br>
			<span style="font-size: 15px; font-weight: bold; color: darkgrey;"> Trump Approval Rating: @month_approval{0,0.0}%</span><br>
			<span style="font-size: 15px; font-weight: bold; color: blue;"> Generic Democrat: @month_generic_dem{0,0.0}%</span><br>
			<span style="font-size: 15px; font-weight: bold; color: red;"> Generic Republican: @month_generic_rep{0,0.0}%</span><br>
			<span style="font-size: 17px; font-weight: bold;"> NASDAQ: @month_nasdaq{0,0.00}</span><br>
			<span style="font-size: 17px; font-weight: bold;"> DJIA: @month_djia{0,0.00}</span><br>
			<span style="font-size: 17px; font-weight: bold;">S&P500: @month_sp500{0,0.00}</span><br>
		</div>
		<div>
			<img
			src="/static/img/nyt_logo.png" height="15" width="15"
			style="float: left;"></img>
		</div>
		<div>
			<span style="font-size: 17px; font-weight: bold;">NYT Headlines:</span>
			<span style="font-size: 15px;">@month_nyt</span>
		</div>
		<div>
			<img
			src="/static/img/twitter_logo.png" height="15" width="15"
			style="float: left;"></img>
		</div>
		<div>
			<span style="font-size: 17px; color:blue; font-weight: bold;">Trending Tweets:</span>
			<span style="font-size: 15px; color:blue;">@month_twitter</span>
		</div>
	</div>
	"""

    hover_tool = HoverTool(renderers=[rect_renderer], tooltips=TOOLTIPS)
    # hover_tool = HoverTool(renderers=[rect_renderer], tooltips=[("Holiday", "@month_holidays"),("DJIA", "@month_djia{0,0.00}"),
    # 	("NASDAQ", "@month_nasdaq{0,0.00}"),("S&P500", "@month_sp500{0,0.00}"),("NYT Headlines", "@month_nyt"),("Trending Tweets","@month_twitter")])
    plot.tools.append(hover_tool)

    return plot