コード例 #1
0
ファイル: Heatmap.py プロジェクト: zie225/lux
    def initialize_chart(self):
        # return NotImplemented
        x_attr = self.vis.get_attr_by_channel("x")[0]
        y_attr = self.vis.get_attr_by_channel("y")[0]

        chart = (alt.Chart(self.data).mark_rect().encode(
            x=alt.X(
                "xBinStart",
                type="quantitative",
                axis=alt.Axis(title=x_attr.attribute),
                bin=alt.BinParams(binned=True),
            ),
            x2=alt.X2("xBinEnd"),
            y=alt.Y(
                "yBinStart",
                type="quantitative",
                axis=alt.Axis(title=y_attr.attribute),
                bin=alt.BinParams(binned=True),
            ),
            y2=alt.Y2("yBinEnd"),
            opacity=alt.Opacity(
                "count",
                type="quantitative",
                scale=alt.Scale(type="log"),
                legend=None,
            ),
        ))
        chart = chart.configure_scale(minOpacity=0.1, maxOpacity=1)
        # Setting tooltip as non-null
        chart = chart.configure_mark(tooltip=alt.TooltipContent("encoding"))
        chart = chart.interactive()  # Enable Zooming and Panning

        ####################################
        # Constructing Altair Code String ##
        ####################################

        self.code += "import altair as alt\n"
        # self.code += f"visData = pd.DataFrame({str(self.data.to_dict(orient='records'))})\n"
        self.code += f"visData = pd.DataFrame({str(self.data.to_dict())})\n"
        self.code += f"""
		chart = alt.Chart(visData).mark_rect().encode(
			x=alt.X('xBinStart', type='quantitative', axis=alt.Axis(title='{x_attr.attribute}'), bin = alt.BinParams(binned=True)),
			x2=alt.X2('xBinEnd'),
			y=alt.Y('yBinStart', type='quantitative', axis=alt.Axis(title='{y_attr.attribute}'), bin = alt.BinParams(binned=True)),
			y2=alt.Y2('yBinEnd'),
			opacity = alt.Opacity('count',type='quantitative',scale=alt.Scale(type="log"),legend=None)
		)
		chart = chart.configure_mark(tooltip=alt.TooltipContent('encoding')) # Setting tooltip as non-null
		"""
        return chart
コード例 #2
0
    def initialize_chart(self):
        # return NotImplemented
        x_attr = self.vis.get_attr_by_channel("x")[0]
        y_attr = self.vis.get_attr_by_channel("y")[0]
        # x_min = self.vis.min_max[x_attr.attribute][0]
        # x_max = self.vis.min_max[x_attr.attribute][1]

        # y_min = self.vis.min_max[y_attr.attribute][0]
        # y_max = self.vis.min_max[y_attr.attribute][1]

        chart = alt.Chart(self.data).mark_rect().encode(
            x=alt.X('xBinStart',
                    type='quantitative',
                    axis=alt.Axis(title=x_attr.attribute),
                    bin=alt.BinParams(binned=True)),
            x2=alt.X2('xBinEnd'),
            y=alt.Y('yBinStart',
                    type='quantitative',
                    axis=alt.Axis(title=y_attr.attribute),
                    bin=alt.BinParams(binned=True)),
            y2=alt.Y2('yBinEnd'),
            #opacity = alt.Opacity('z',type='quantitative',scale=alt.Scale(type="log"))
            color=alt.Color('z',
                            type='quantitative',
                            scale=alt.Scale(scheme='blues', type="log"),
                            legend=None))
        chart = chart.configure_mark(tooltip=alt.TooltipContent(
            'encoding'))  # Setting tooltip as non-null
        chart = chart.interactive()  # Enable Zooming and Panning

        ####################################
        # Constructing Altair Code String ##
        ####################################

        self.code += "import altair as alt\n"
        # self.code += f"visData = pd.DataFrame({str(self.data.to_dict(orient='records'))})\n"
        self.code += f"visData = pd.DataFrame({str(self.data.to_dict())})\n"
        self.code += f'''
		chart = alt.Chart(visData).mark_rect().encode(
			x=alt.X('xBinStart', type='quantitative', axis=alt.Axis(title='{x_attr.attribute}'), bin = alt.BinParams(binned=True)),
			x2=alt.X2('xBinEnd'),
			y=alt.Y('yBinStart', type='quantitative', axis=alt.Axis(title='{y_attr.attribute}'), bin = alt.BinParams(binned=True)),
			y2=alt.Y2('yBinEnd'),
			#opacity = alt.Opacity('z',type='quantitative',scale=alt.Scale(type="log"))
			color = alt.Color('z',type='quantitative', scale=alt.Scale(scheme='blues',type="log"),legend=None)
		)
		chart = chart.configure_mark(tooltip=alt.TooltipContent('encoding')) # Setting tooltip as non-null
		'''
        return chart
コード例 #3
0
 def histogram(tag):
     """
     Produces a single histogram for a tag.
     :param tag: the tag to use the data of for the histogram
     :type tag: str
     :return: the produced graph
     """
     data = []
     for chromosome in ChromosomeController.nondominatedFront:
         tags = [tuple(["Health"]) + tuple(chromosome.health), tuple(["Magic"]) + tuple(chromosome.magic)] \
                    + chromosome.tags
         tagIndex = chromosome.get_tag_index(tag) + 2
         if tag == "Health":
             tagIndex -= 1
         data.append({"Weighting": tags[tagIndex][2]})
     data = pd.DataFrame(data)
     chart = alt.Chart(data).mark_bar().encode(
         x=alt.X("Weighting", bin=alt.BinParams(maxbins=10, minstep=1)),
         y="count()",
     ).properties(
         title=tag,
         width=100,
         height=100
     )
     return chart
コード例 #4
0
def returns_histogram(report):
    bar = alt.Chart(report).mark_bar().encode(
        x=alt.X(
            "Interval Change:Q",
            bin=alt.BinParams(maxbins=100),
            axis=alt.Axis(format='%')),
        y="count():Q")
    return bar
コード例 #5
0
ファイル: chloropleth.py プロジェクト: armsp/covid19.in
def make_chloropleth_json(clean_state_dataset_path):
    india = gpd.read_file('india_v2.json')
    files = glob.glob(clean_state_dataset_path+'/2020-*.csv')#../statewise_distribution/2020-*.csv'
    sorted_files = sorted(files, key=lambda d: tuple(map(int, d.split('/')[-1].split('.')[0].split('-'))))
    #print(sorted_files)
    latest_file = sorted_files[-1]
    print(latest_file)
    df = pd.read_csv(latest_file)
    df = df.drop(['sno.', 'lon', 'lat', 'day'], 1)
    df.rename(columns={'recovery': 'Recovery', 'death': 'Deaths'}, inplace=True)
    df['Active Cases'] = df['case'] - df['Recovery'] - df['Deaths']

    india = india.join(df.set_index('place'), on='state')

    # Mapping
    base = alt.Chart(india).mark_geoshape(fill='white', stroke='gray', strokeWidth=2).encode().properties(
            width='container',
            height=525,
        )

    choro = alt.Chart(india,width='container',height=525,).mark_geoshape(
            #fill='lightgray',
            fillOpacity=0.8,
            strokeWidth=1,
            stroke='gray',
        ).encode(
            color=alt.Color('Active Cases',
                    type='quantitative',
                    scale=alt.Scale(scheme='orangered',type='sqrt'),#sqrt band
                    #['linear', 'log', 'pow', 'sqrt', 'symlog', 'identity', 'sequential', 'time', 'utc', 'quantile', 'quantize', 'threshold', 'bin-ordinal', 'ordinal', 'point', 'band']
                    title = "Active Cases",
                    bin=alt.BinParams(binned=False,maxbins=32,nice=True),
                    legend=None
                    ),
            tooltip=[alt.Tooltip('state:N', title='State'),'Active Cases:Q', 'Deaths:Q', 'Recovery:Q'],
        )

    final_map = (base+choro).configure_view(
        strokeWidth=0
    )
    # .configure_legend(
    #     # orient='bottom',
    #     gradientLength = 500
    # )
    # kwargs = {'actions': False}
    return final_map.to_json(indent=None)
# with open('charts.html', 'w') as f:
#     f.write(two_charts_template.format(
#         vega_version=alt.VEGA_VERSION,
#         vegalite_version=alt.VEGALITE_VERSION,
#         vegaembed_version=alt.VEGAEMBED_VERSION,
#         spec1=final_map.to_json(indent=None),
#         # spec2=final_map.to_json(indent=None),
#     ))
コード例 #6
0
    x=alt.X("mean(Production_Budget):Q"), y=alt.Y("Major_Genre:N"))
bar2 = alt.Chart(movies).mark_bar().encode(
    x=alt.X("median(Production_Budget):Q"), y=alt.Y("Major_Genre:N"))

bar1 | bar2
"""You can also build more sophisticated visualizations by combining charts both horizontally and vertically. For example, this next plot is known as a scatterplot with marginal historgrams. In the middle we are looking at the correlation between Rotten Tomatoes and IMDB scores. On the top and right we see the distributions of each variable separately. In this case we see a weak correlation and also note the IMDB rating has a nice normal distribution but the Rotten tomatoes scores seem more uniform."""

# 1.3

# # scatter plot for the middle
points = alt.Chart(movies).mark_point(filled=True, size=90).encode(
    x=alt.X('IMDB_Rating'), y=alt.Y('Rotten_Tomatoes_Rating'))

# the histogram to put on the right side (notice we remove the axes)
distribright = alt.Chart(movies).mark_bar().encode(
    y=alt.Y('Rotten_Tomatoes_Rating', bin=alt.BinParams(maxbins=20),
            axis=None),
    x=alt.X('count()', axis=None),
).properties(width=30)

# the histogram to put on the top (notice we remove the axes)
distribtop = alt.Chart(movies).mark_bar().encode(
    x=alt.X('IMDB_Rating', bin=alt.BinParams(maxbins=20), axis=None),
    y=alt.Y('count()', axis=None),
).properties(height=30)

# put the scatter and right together side by side and then put those
# under the top histogram
distribtop & (points | distribright)
"""[Layering](https://altair-viz.github.io/user_guide/compound_charts.html#layered-charts) is a very useful compounding method that allows you to overlay two different charts on the same set of axes. You can layer charts using the "+" operator."""
alt.Chart(mtcars).mark_bar().encode(
    x=alt.X('transmission:N', bin=True),
    y=alt.Y('max(HP)'),
)
"""We can bin data based on numerical properties as well. For example, we can generate a histogram of weights for our cars:"""

#3.8
alt.Chart(mtcars).mark_bar().encode(
    x=alt.X('weight'),
    y=alt.Y('count()'),
)
"""As with most things in Altair, bins can be modified by using a special function to generate additional grammar of graphics commands. Bins, in particular, can be modified with the [BinParams](https://altair-viz.github.io/user_guide/generated/core/altair.BinParams.html#altair.BinParams) method. A simple example is making more bins:"""

#3.9
alt.Chart(mtcars).mark_bar().encode(
    x=alt.X('weight', bin=alt.BinParams(maxbins=20)),
    y=alt.Y('count()'),
)
"""## 4 Sorting
In addition to binning, Altair also supports other transformations. Sorting is one of the most useful ones and is fairly easy. Below, we take our original bar chart showing the MPG for each car and add a sort on the Y-axis (the cars). We use the `EncodingSortField` function indicating that we want the models sorted by MPG (in descending order). More information on sorting can be found [here](https://altair-viz.github.io/user_guide/generated/core/altair.EncodingSortField.html).
"""

#4.1
alt.Chart(mtcars).mark_bar().encode(
    x='MPG',
    y=alt.Y(
        'model',
        sort=alt.EncodingSortField(
            field="MPG",  # The field to use for the sort
            order="descending"  # The order to sort in
        )))
コード例 #8
0
def histogram_emissions(
        data,
        title,
        base_url="https://sustainable-recipe-recommender.herokuapp.com/search/"
):
    """
    DESCRIPTION:
        Creates a histogram of emission scores of a list of reference
        recipes, with the distribution of all emission scores as the
        background.

    INPUT:
        data (pandas.DataFrame): With columns
            Emissions (Float): log10-scaled emission scores
            url (String): recipe url (e.g. "pineapple-shrimp-noodles")
            Title (String): recipe title (e.g. "Pineapple shrimp noodles")
            reference (boolean): True for all reference recipes to highlight
        title (String): Figure title
        base_url (String): Base url of the recipe search website

    OUTPUT:
        Altair json object
    """
    alt.data_transformers.disable_max_rows()  # TODO find a better solution

    col = "#1f77b4"  # try different color?

    # background chart (histogram of all emissions)
    source = data
    bg_chart = (alt.Chart(source).mark_area(
        color=col,
        opacity=0.3,
    ).encode(
        alt.X(
            "log10(Emissions):Q",
            axis=alt.Axis(title="log10(Emissions (kg CO2 eq.))"),
            scale=alt.Scale(type="linear", domain=(-1.0, 2.0)),
            bin=alt.BinParams(maxbins=300),
        ),
        alt.Y("count(*):Q",
              axis=alt.Axis(title="Number of recipes (all)"),
              stack=None),
    ).properties(width=800, height=300, title=title))

    # foreground chart - e.g. cookbook recipes
    source = data.loc[data["reference"], :]
    fg_chart = (alt.Chart(source).transform_calculate(
        link=base_url + alt.datum.url + "?sort_by=" +
        "Similarity").mark_bar(color=col).encode(
            x=alt.X(
                "log10(Emissions):Q",
                scale=alt.Scale(type="linear", domain=(-1.0, 2.0)),
                bin=alt.BinParams(maxbins=200),
            ),
            y=alt.Y("count(*):Q", axis=None, stack=None),
            tooltip=["Title", "Emissions"],
            href="link:N",
        ).properties(width=800, height=300).interactive())

    # Set different y-axes for background and foreground and make pretty
    full_chart = (alt.layer(
        bg_chart, fg_chart).resolve_scale(y="independent").configure_axis(
            labelFontSize=16,
            titleFontSize=16,
            labelFontWeight="normal",
            titleFontWeight="normal",
            labelColor="gray",
            titleColor="gray",
        ).configure_title(fontSize=22, fontWeight="normal"))

    return full_chart.to_json()
コード例 #9
0
"""
Table Binned Heatmap
-----------------------
This example shows how to make a heatmap.
"""

import altair as alt
from vega_datasets import data

source = data.movies()

chart = alt.Chart(source).mark_rect().encode(
    x=alt.X('IMDB_Rating', bin=alt.BinParams(maxbins=60)),
    y=alt.Y('Rotten_Tomatoes_Rating', bin=alt.BinParams(maxbins=40)),
    color=alt.Color('count(IMDB_Rating)', scale=alt.Scale(scheme='greenblue')))