question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Adding bar that represents a variable in a dataset to a visualization

See original GitHub issue

Hi Jake,

I followed guide: https://altair-viz.github.io/gallery/us_population_over_time.html and was able to successfully create histogram along with slider. However, I would like to add another bar next to my current bar,which is my s2 column in dataset.So far, I tried inserting s2 in my below code. It didn’t work and returned empty plot: y=alt.Y('sum(s1,s2):Q', scale=alt.Scale(domain=(0,120000000))), I was wondering if something like that can be achievable ? Also, I was wondering if I can display two years (i.e 1920,1925) on single selection ? My code so far look like following.

image

Code:

from altair.expr import datum, if_

pink_blue = alt.Scale(domain=('PA', 'DC', 'TX'),
                      range=["steelblue", "salmon","Orange")

slider = alt.binding_range(min=1920, max=1930, step=1)
select_year = alt.selection_single(name="Year", fields=['Year'], bind=slider)
alt.Chart(df3).mark_bar().encode(
    x=alt.X('Year:N', axis=alt.Axis(title=None)),
    y=alt.Y('sum(s1):Q', scale=alt.Scale(domain=(0,120000000))),
    color=alt.Color('Area:N', scale=pink_blue),
    column='Area:O'
).properties(
    width=450
).add_selection(select_year).transform_filter(select_year).properties(width=100)

Altair Rocks!!! 😃

Thanks in advance,

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:12 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
smitpate08commented, Aug 26, 2018

@jakevdp That will be awesome 😃

1reaction
lincolnfriascommented, Aug 26, 2018

It is possible to use altair in Kaggle, but you need to enable the notebook renderer:

alt.renderers.enable('notebook')

With this you get even the interactions when you are working on a kernel. But the charts will not work when other people see the static version of it. For this, the strategy people are using is to do the following (source):

import altair as alt
from  altair.vega import v3
import json

vega_url = 'https://cdn.jsdelivr.net/npm/vega@' + v3.SCHEMA_VERSION
vega_lib_url = 'https://cdn.jsdelivr.net/npm/vega-lib'
vega_lite_url = 'https://cdn.jsdelivr.net/npm/vega-lite@' + alt.SCHEMA_VERSION
vega_embed_url = 'https://cdn.jsdelivr.net/npm/vega-embed@3'
noext = "?noext"

paths = {
    'vega': vega_url + noext,
    'vega-lib': vega_lib_url + noext,
    'vega-lite': vega_lite_url + noext,
    'vega-embed': vega_embed_url + noext
}

workaround = """
requirejs.config({{
    baseUrl: 'https://cdn.jsdelivr.net/npm/',
    paths: {}
}});
"""

def add_autoincrement(render_func):
    # Keep track of unique <div/> IDs
    cache = {}
    def wrapped(chart, id="vega-chart", autoincrement=True):
        if autoincrement:
            if id in cache:
                counter = 1 + cache[id]
                cache[id] = counter
            else:
                cache[id] = 0
            actual_id = id if cache[id] == 0 else id + '-' + str(cache[id])
        else:
            if id not in cache:
                cache[id] = 0
            actual_id = id
        return render_func(chart, id=actual_id)
    # Cache will stay outside and 
    return wrapped
            
@add_autoincrement
def render(chart, id="vega-chart"):
    chart_str = """
    <div id="{id}"></div><script>
    require(["vega-embed"], function(vg_embed) {{
        const spec = {chart};     
        vg_embed("#{id}", spec, {{defaultStyle: true}}).catch(console.warn);
        console.log("anything?");
    }});
    console.log("really...anything?");
    </script>
    """
    return HTML(
        chart_str.format(
            id=id,
            chart=json.dumps(chart) if isinstance(chart, dict) else chart.to_json(indent=None)
        )
    )

HTML("".join((
    "<script>",
    workaround.format(json.dumps(paths)),
    "</script>",
    "This code block sets up embedded rendering in HTML output and<br/>",
    "provides the function `render(chart, id='vega-chart')` for use below."
)))

The you need to name your chart and pass it as an argument to the render function:

data = pd.DataFrame({'a': list('CCCDDDEEE'),
                     'b': [2, 7, 4, 1, 2, 6, 8, 4, 7]})

chart = alt.Chart(data).mark_point().encode(
    x = 'a',
    y = 'b'
)

render(chart, id='vega-chart')
Read more comments on GitHub >

github_iconTop Results From Across the Web

A Complete Guide to Bar Charts | Tutorial by Chartio
Bar charts are a fundamental visualization for comparing values between groups of data. ... The primary variable of a bar chart is its...
Read more >
How to Make a Bar Graph With 3 Variables in Excel & Google ...
Data in a Bar graph with 3 variables is displayed using vertical or horizontal bars. The length or height of each bar is...
Read more >
Quantitative comparisons and statistical visualizations
A stacked bar chart contains bars, where the height of each bar represents values. In addition, stacked on top of the first variable...
Read more >
Visualizing a Categorical Variable
The bar chart is often used to show the frequencies of a categorical variable. By default, geom_bar uses stat = "count" and maps...
Read more >
Bar Plots in Python | Beginner's Guide to Data Visualization ...
The length and heights of the bar chart represent the data distributed in the dataset. In a bar chart, we have one axis...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found