Exemple #1
0
 def gen(self,
         slug,
         name,
         dataobj,
         xfield,
         yfield,
         time_unit=None,
         chart_type="line",
         width=800,
         height=300,
         color=Color(),
         size=Size(),
         scale=Scale(zero=False),
         shape=Shape(),
         filepath=None,
         html_before="",
         html_after=""):
     """
     Generates an html chart from either a pandas dataframe, a dictionnary,
     a list or an Altair Data object and optionally write it to a file
     """
     chart_obj = self.serialize(dataobj, xfield, yfield, time_unit,
                                chart_type, width, height, color, size,
                                scale, shape)
     html = self.html(slug, name, chart_obj, filepath, html_before,
                      html_after)
     return html
Exemple #2
0
def visualize(result, fileName):
    from altair import Chart, Color, Y, Scale

    #chart = LayeredChart(result)
    #chart += Chart().mark_line().encode(x='Search:O', y='Elapsed Time:Q')

    chart = Chart(result).mark_point().encode(x='Search:O',
                                              color='Problem:O',
                                              y=Y('Elapsed Time:Q',
                                                  scale=Scale(type='log')))
    #x='Search:O', color='Problem:O', y='Elapsed Time:Q')
    #    with open('out.html', 'w') as f:
    #       f.write(html)
    chart.savechart(fileName + ".l.svg")
Exemple #3
0
 def _encode_fields(self,
                    xfield,
                    yfield,
                    time_unit=None,
                    scale=Scale(zero=False)):
     """
     Encode the fields in Altair format
     """
     if scale is None:
         scale = Scale()
     xfieldtype = xfield[1]
     yfieldtype = yfield[1]
     x_options = None
     if len(xfield) > 2:
         x_options = xfield[2]
     y_options = None
     if len(yfield) > 2:
         y_options = yfield[2]
     if time_unit is not None:
         if x_options is None:
             xencode = X(xfieldtype, timeUnit=time_unit)
         else:
             xencode = X(xfieldtype,
                         axis=Axis(**x_options),
                         timeUnit=time_unit,
                         scale=scale)
     else:
         if x_options is None:
             xencode = X(xfieldtype)
         else:
             xencode = X(xfieldtype, axis=Axis(**x_options), scale=scale)
     if y_options is None:
         yencode = Y(yfieldtype, scale=scale)
     else:
         yencode = Y(yfieldtype, axis=Axis(**y_options), scale=scale)
     return xencode, yencode
Exemple #4
0
def color_heatmap(data,
                  row,
                  column,
                  column_to_color,
                  colormap_domain,
                  colormap_range,
                  cellsize=(10, 10)):
    """Create an Altair/vega-lite Heat-Map with colormap parameter

    Parameters
    ----------
    data : dataframe to display, or url of csv file
    row, column, color, column_to_color : str
        Altair trait shorthands
    colormap_domain : list of strings - html color names, or hex value strings
    colormap_range : list of normalized values binned to colormap_domain
    cellsize : tuple
        specify (width, height) of cells in pixels
    """

    return Chart(data).mark_text(applyColorToBackground=True, ).encode(
        color=Color(
            column_to_color,
            legend=Legend(
                orient='right',
                title=column_to_color,
                #                   # visible values in legend labels:
                #                   # in order to avoid blob of legend labels
                #                   # display only the max and min of values in given domain
                values=[colormap_domain[0], colormap_domain[-1]],
                labelAlign='left',
            ),
            scale=Scale(domain=colormap_domain, range=colormap_range),
        ),
        column=Column(
            column,
            axis=Axis(
                labelAngle=270.0,
                orient='bottom',
                title=column,
            ),
        ),
        row=row,
        text=Text(value=' ', ),
    ).configure_scale(textBandWidth=cellsize[0], bandSize=cellsize[1])
Exemple #5
0
def plotter(name, x, label):
    df = pandas.DataFrame({
        "x": [el[0] for el in x],
        "y": [el[1] for el in x],
        "z": [el[2] for el in x]
    })
    chart = alt.Chart(
        df, title=label[2], width=60, height=600).mark_bar().encode(
            column=Column('x', title=label[3], spacing=75),
            x=X('z', title=""),
            y=Y('y', title=label[4]),
            color=Color(
                'z', title=label[5],
                scale=Scale(range=['#6fbf4a', '#5f249f']))).configure_view(
                    strokeWidth=0.0, width=300)

    chart = chart.configure_title(fontSize=25, offset=15)
    chart.save(f"{name}.html")
def covid_demo():

    interval = selection_interval()

    circle = Chart(selected_data).mark_circle().encode(
        x='monthdate(Date):O',
        y='Country/Region',
        color=condition(interval, 'Country/Region', value('lightgray')),
        size=Size('New cases:Q',
                  scale=Scale(range=[0, 3000]),
                  legend=Legend(title='Daily new cases'))).properties(
                      width=1000, height=300, selection=interval)

    bars = Chart(selected_data).mark_bar().encode(
        y='Country/Region', color='Country/Region',
        x='sum(New cases):Q').properties(width=1000).transform_filter(interval)

    chart = circle & bars

    return chart.to_json()
Exemple #7
0
        def getBaseChart():
            """
              Creates a chart by encoding the Data along the X positional axis and rolling mean along the Y positional axis
            """

            base = (
                alt.Chart(data)
                    .encode(
                    x=alt.X(
                        "Date:T",
                        axis=alt.Axis(title=None, format=("%b %Y"), labelAngle=0),
                    ),
                    y=alt.Y(
                        "grade:Q",
                        axis=alt.Axis(title=None),
                        scale=Scale(domain=(0, 5))
                    ),
                    color=alt.Color('course:N', legend=None)
                ).properties(width=400, height=336)
            )

            return base
Exemple #8
0
 def serialize(self,
               dataobj,
               xfield,
               yfield,
               time_unit=None,
               chart_type="line",
               width=800,
               height=300,
               color=None,
               size=None,
               scale=Scale(zero=False),
               shape=None,
               options={}):
     """
     Serialize to an Altair chart object from either a pandas dataframe, a dictionnary,
     a list or an Altair Data object
     """
     dataset = dataobj
     if self._is_dict(dataobj) is True:
         dataset = self._dict_to_df(dataobj, xfield, yfield)
     elif isinstance(dataobj, list):
         dataset = Data(values=dataobj)
     xencode, yencode = self._encode_fields(xfield, yfield, time_unit)
     opts = dict(x=xencode, y=yencode)
     if color is not None:
         opts["color"] = color
     if size is not None:
         opts["size"] = size
     if shape is not None:
         opts["shape"] = shape
     chart = self._chart_class(dataset, chart_type,
                               **options).encode(**opts).configure_cell(
                                   width=width,
                                   height=height,
                               )
     return chart
print("Greedy Algorithm Execution Time: %s seconds" %
      (time.time() -
       start_time))  # Timer ends after greedy search ran successfully
print('knapsack:', kn2)
print('optimum weight:', optimum_w2)
print('optimum value:', optimum_v2)
print("Exhaustive total value / Greedy total value = ",
      optimum_v1 / optimum_v2)

df = pd.read_csv('/Users/alexallenspach/Documents/CS4720/HW2_PlotsData.csv')

alt.data_transformers.enable('default', max_rows=None)

chart1 = alt.Chart(df).mark_circle(size=50).encode(
    Color('Algorithm:N',
          scale=Scale(domain=['Exhaustive', 'Greedy'],
                      range=['#1f77b4', '#e377c2'])),
    x=alt.X('n:Q', scale=alt.Scale(zero=False)),
    y=alt.Y('Time:Q', scale=alt.Scale(zero=False)),
    tooltip=['n', 'Time', 'Algorithm'],
    opacity=alt.value(1)).properties(background='white')

chart1
chart.save('scatterPlot1.png', scale_factor=2.0)

df = pd.read_csv('/Users/alexallenspach/Documents/CS4720/HW2_PlotsData.csv')

alt.data_transformers.enable('default', max_rows=None)

chart2 = alt.Chart(df).mark_circle(size=50).encode(
    Color('Algorithm:N',
          scale=Scale(domain=['Exhaustive', 'Greedy'],
Exemple #10
0
def hc_grade():
    session_id = os.environ.get("SESSION_ID")
    selected_course = session.get('selected_course', None)
    # show all course grades if haven't selected course from dropdown
    if selected_course == None:
        HcData = pd.read_sql(db.session.query(Hc).filter_by(user_id=session_id).statement, db.session.bind)
        final = Chart(
            data=HcData, height=1000, width=380).mark_bar().encode(
            X('mean:Q',
              axis=alt.Axis(title='HC Forum Score'),
              scale=Scale(domain=(0, 5))
              ),
            alt.Y('name:N',
            sort=alt.EncodingSortField(field= "mean", op="sum", order = "descending")
            ,axis=alt.Axis(title=None)
            ),
            color='course:N')#.interactive()
    else:
        # query data
        df = grade_calculations.hc_grade_over_time(session_id, selected_course)

        longdata = df.melt('Date', var_name='course', value_name='grade')
        data = longdata[longdata['grade'].notnull()]

        def getBaseChart():
            """
              Creates a chart by encoding the Data along the X positional axis and rolling mean along the Y positional axis
            """

            base = (
                alt.Chart(data)
                    .encode(
                    x=alt.X(
                        "Date:T",
                        axis=alt.Axis(title=None, format=("%b %Y"), labelAngle=0),
                    ),
                    y=alt.Y(
                        "grade:Q",
                        axis=alt.Axis(title=None),
                        scale=Scale(domain=(0, 5))
                    ),
                    color=alt.Color('course:N', legend=None)
                ).properties(width=400, height=336)
            )

            return base

        def getSelection():
            """
              This function creates a selection element and uses it to conditionally set a color for a categorical variable (course).
              It return both the single selection as well as the Category for Color choice set based on selection.
            """
            radio_select = alt.selection_multi(
                fields=["course"], name="Course",
            )

            course_color_condition = alt.condition(
                radio_select, alt.Color("course:N", legend=None), alt.value("lightgrey")
            )

            return radio_select, course_color_condition

        def createChart():
            """
              This function uses the "base" encoding chart to create a line chart.
              The highlight_course variable uses the mark_line function to create a line chart out of the encoding.
              The color of the line is set using the conditional color set for the categorical variable using the selection.
              The chart is bound to the selection using add_selection.
              It also creates a selector element of a vertical array of circles so that the user can select between courses.
            """

            radio_select, course_color_condition = getSelection()

            make_selector = (
                alt.Chart(data)
                    .mark_circle(size=220)
                    .encode(
                    y=alt.Y("course:N", title="Click on circle"),
                    color=course_color_condition
                ).add_selection(radio_select)
            )

            base = getBaseChart()

            highlight_course = (
                base.mark_line(strokeWidth=2)
                    .add_selection(radio_select)
                    .encode(color=course_color_condition,
                            opacity=alt.condition(radio_select, alt.value(1.0), alt.value(0.2)))
            ).properties(title="Rolling Weighted Average of Cornerstone Courses")

            return base, make_selector, highlight_course, radio_select

        def createTooltip(base, radio_select):
            """
              This function uses the "base" encoding chart and the selection captured.
              Four elements related to selection are created here
            """
            # Create a selection that chooses the nearest point & selects based on x-value
            nearest = alt.selection(
                type="single", nearest=True, on="mouseover", fields=["Date"], empty="none"
            )

            # Transparent selectors across the chart. This is what tells us
            # the x-value of the cursor
            selectors = (
                alt.Chart(data)
                    .mark_point()
                    .encode(
                    x="Date:T",
                    opacity=alt.value(0),
                ).add_selection(nearest)
            )

            # Draw points on the line, and highlight based on selection
            points = base.mark_point().encode(
                color=alt.Color("course:N", legend=None),
                opacity=alt.condition(nearest, alt.value(1), alt.value(0))
            ).transform_filter(radio_select)

            # Draw text labels near the points, and highlight based on selection
            tooltip_text = base.mark_text(
                align="left",
                dx=5,
                dy=-5,
                fontSize=12
                # fontWeight="bold"
            ).encode(
                text=alt.condition(
                    nearest,
                    alt.Text("grade:Q", format=".2f"),
                    alt.value(" "),
                ),
            ).transform_filter(radio_select)

            # Draw a rule at the location of the selection
            rules = (
                alt.Chart(data)
                    .mark_rule(color="black", strokeWidth=1)
                    .encode(
                    x="Date:T",
                ).transform_filter(nearest)
            )

            return selectors, rules, points, tooltip_text

        base, make_selector, highlight_course, radio_select = createChart()
        selectors, rules, points, tooltip_text = createTooltip(base, radio_select)
        # Bring all the layers together with layering and concatenation
        final = (make_selector | alt.layer(highlight_course, selectors, points, rules, tooltip_text))
    return final.to_json()
Exemple #11
0
def course_grade():
    session_id = os.environ.get("SESSION_ID")
    selected_course = session.get('selected_course', None)
    # show all course grades if haven't selected course from dropdown
    if selected_course == None:
        source = pd.read_sql(grade_calculations.Co_grade_query(user_id=session_id).statement, db.session.bind)

        # make chart here
        bar = alt.Chart(
            data=source).mark_bar().encode(
            Y('cograde:Q',
              scale=Scale(domain=(0, 5))
              ),
            alt.X('course:N',
                    sort=alt.EncodingSortField(field= "cograde", op="sum", order = "descending")),
            #color=alt.Color('course:N', legend=None))#.interactive()
            color=alt.Color('major:N'))#.interactive()


        line = alt.Chart(source).mark_rule(color='red').encode(
                 y='mean(cograde):Q'
                )
        chart = alt.layer(
            bar, line
        ).properties(
            width=480, height=336
        )

        # always return to json.
        return chart.to_json()
    else:
        # show individual course trend for the selected course from dropdown list
        source = grade_calculations.co_grade_over_time(user_id=session_id, course=selected_course)

        # make interactive chart
        # Create a selection that chooses the nearest point & selects based on x-value
        nearest = alt.selection(type='single', nearest=True, on='mouseover',
                                fields=['Date'], empty='none')

        # The basic line
        line = alt.Chart(source).mark_line().encode(
            x='Date:N',
            y='Course Grade:Q',
        )

        # Transparent selectors across the chart. This is what tells us
        # the x-value of the cursor
        selectors = alt.Chart(source).mark_point().encode(
            x='Date:N',
            opacity=alt.value(0),
        ).add_selection(
            nearest
        )

        # Draw points on the line, and highlight based on selection
        points = line.mark_point().encode(
            opacity=alt.condition(nearest, alt.value(1), alt.value(0))
        )

        # Draw text labels near the points, and highlight based on selection
        text = line.mark_text(align='left', dx=5, dy=-5).encode(
            text=alt.condition(nearest, 'Course Grade:Q', alt.value(' '))
        )

        # Draw a rule at the location of the selection
        rules = alt.Chart(source).mark_rule(color='gray').encode(
            x='Date:N',
        ).transform_filter(
            nearest
        )

        # Put the five layers into a chart and bind the data
        chart = alt.layer(
            line, selectors, points, rules, text
        ).properties(
            width=500, height=336
        )

        return chart.to_json()
Exemple #12
0
data.to_json(path_or_buf=json_filename, orient='records', date_format='iso')
#data.to_csv(path_or_buf=csv_filename)

colors = [
    "#67001f", "#b2182b", "#d6604d", "#f4a582", "#fddbc7", "#d1e5f0",
    "#92c5de", "#4393c3", "#2166ac", "#053061"
]

colors = colors[::-1]

#d = [0, 12, 24, 36, 48, 60, 72, 84, 96, 108]
d = [0, 120]
r = Row('dt:T', timeUnit='hours', axis=Axis(title='Hour of day'))
c = Column('dt:T',
           timeUnit='monthdate',
           axis=Axis(format=u'%b', labels=False, title='Month'))
col = Color(
    'temp:N',
    bin=Bin(step=12),
    scale=Scale(domain=[0, 120], range=colors, clamp=True, zero=True),
    #scale=Scale(range=colors, domain=[0, 120], zero=True),
    legend=Legend(title="Temperature", format=u'.0f'))

chart = Chart(data).mark_text(applyColorToBackground=True).encode(
    row=r, column=c, text=Text('blanks'),
    color=col).configure_scale(textBandWidth=3, bandSize=25)

chart.max_rows = 8761
filename = sys.argv[2] + ".html"
chart.savechart(filename)
import altair as alt
import pandas as pd
from altair import Color, Scale

df = pd.read_csv('/Users/saranking/weight-height.csv')

alt.data_transformers.enable('default', max_rows=None)

chart = alt.Chart(df).mark_point().encode(
    Color('Gender:N',
          scale=Scale(domain=['Male', 'Female'], range=['#1f77b4',
                                                        '#e377c2'])),
    x=alt.X('Height_in:Q', scale=alt.Scale(zero=False)),
    y=alt.Y('Weight_lbs:Q', scale=alt.Scale(zero=False)),
    tooltip=['Height_in', 'Weight_lbs', 'Gender'],
    opacity=alt.value(0.45)).properties(background='white')

chart
chart.save('scatterPlot.png', scale_factor=2.0)