Altair: Latest version of altair seems to have broken LayeredChart()

Created on 22 Oct 2017  ·  12Comments  ·  Source: altair-viz/altair

I tried this code both on desktop Jupyter notebook and in Azure notebook. It used to work in both.

With appropriately defined pandas dataframe named 'data'
c=LayeredChart(data) c+=Chart().mark_line(color='green').encode(x="x",y="y") c+=Chart().mark_line(color='blue').encode(x='x',y='y2') c

This produces the error:

AttributeErrorTraceback (most recent call last)
/home/nbuser/anaconda2_410/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
    913             method = get_real_method(obj, self.print_method)
    914             if method is not None:
--> 915                 method()
    916                 return True
    917 

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc in _ipython_display_(self)
    443         from IPython.display import display
    444         from vega import VegaLite
--> 445         display(VegaLite(self.to_dict(validate_columns=True)))
    446 
    447     def display(self):

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc in to_dict(self, data, validate_columns)
    287             The JSON specification of the chart object.
    288         """
--> 289         dct = super(TopLevelMixin, self.clone()).to_dict(data=data, validate_columns=validate_columns)
    290         dct['$schema'] = schema.vegalite_schema_url
    291         return dct

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/schema/_interface/jstraitlets.pyc in to_dict(self, **kwargs)
    151     def to_dict(self, **kwargs):
    152         """Output a (nested) dict encoding the contents of this instance"""
--> 153         self._finalize(**kwargs)
    154         Visitor = self._converter_registry.get('to_dict', ToDict)
    155         return Visitor().visit(self, **kwargs)

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc in _finalize(self, **kwargs)
    503         # and the Chart allows it.
    504         if validate_columns and self.validate_columns:
--> 505             self._validate_columns()
    506 
    507     def _finalize_data(self):

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc in _validate_columns(self)
    569             # Find columns with visual encodings
    570             encoded_columns = set()
--> 571             encoding = self.encoding
    572             if encoding is not jst.undefined:
    573                 for channel_name in encoding.channel_names:

AttributeError: 'LayeredChart' object has no attribute 'encoding'

Out[9]:
<traitlets.traitlets.LayeredChart at 0x7f6b1c605750>

Most helpful comment

alt.layer(points, lines, data = df) will work.
Altair 2.0.1 has totally new syntax for layered charts as vega-lite 2 do. Please check documentation on compound charts.

All 12 comments

Ohh, that is a bug, I know how to fix it, but we will need to release a bug
fix.

On Sat, Oct 21, 2017 at 7:12 PM, Mark Sawula notifications@github.com
wrote:

I tried this code both on desktop Jupyter notebook and in Azure notebook.
It used to work in both.

With appropriately defined pandas dataframe named 'data'
c=LayeredChart(data) c+=Chart().mark_line(color='green').encode(x="x",y="y")
c+=Chart().mark_line(color='blue').encode(x='x',y='y2') c
This produces the error:
AttributeErrorTraceback (most recent call last)
/home/nbuser/anaconda2_410/lib/python2.7/site-packages/IPython/core/formatters.pyc
in call(self, obj)
913 method = get_real_method(obj, self.print_method)
914 if method is not None:
--> 915 method()
916 return True
917

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc
in ipython_display(self)
443 from IPython.display import display
444 from vega import VegaLite
--> 445 display(VegaLite(self.to_dict(validate_columns=True)))
446
447 def display(self):

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc
in to_dict(self, data, validate_columns)
287 The JSON specification of the chart object.
288 """
--> 289 dct = super(TopLevelMixin, self.clone()).to_dict(data=data,
validate_columns=validate_columns)
290 dct['$schema'] = schema.vegalite_schema_url
291 return dct

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/
altair/v1/schema/_interface/jstraitlets.pyc in to_dict(self, kwargs)
151 def to_dict(self, *kwargs):
152 """Output a (nested) dict encoding the contents of this instance"""
--> 153 self._finalize(
kwargs)
154 Visitor = self._converter_registry.get('to_dict', ToDict)
155 return Visitor().visit(self, *
kwargs)

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc
in _finalize(self, **kwargs)
503 # and the Chart allows it.
504 if validate_columns and self.validate_columns:
--> 505 self._validate_columns()
506
507 def _finalize_data(self):

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc
in _validate_columns(self)
569 # Find columns with visual encodings
570 encoded_columns = set()
--> 571 encoding = self.encoding
572 if encoding is not jst.undefined:
573 for channel_name in encoding.channel_names:

AttributeError: 'LayeredChart' object has no attribute 'encoding'

Out[9]:


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/altair-viz/altair/issues/424, or mute the thread
https://github.com/notifications/unsubscribe-auth/AABr0DpVaIKRhrEPLotrDV4JNmsx5zflks5suqSbgaJpZM4QByO4
.

--
Brian E. Granger
Associate Professor of Physics and Data Science
Cal Poly State University, San Luis Obispo
@ellisonbg on Twitter and GitHub
[email protected] and [email protected]

Thanks. I’m not very experienced in these matters so I’m relieved it’s a bug and not me!

On Oct 21, 2017, at 10:16 PM, Brian E. Granger notifications@github.com wrote:

Ohh, that is a bug, I know how to fix it, but we will need to release a bug
fix.

On Sat, Oct 21, 2017 at 7:12 PM, Mark Sawula notifications@github.com
wrote:

I tried this code both on desktop Jupyter notebook and in Azure notebook.
It used to work in both.

With appropriately defined pandas dataframe named 'data'
c=LayeredChart(data) c+=Chart().mark_line(color='green').encode(x="x",y="y")
c+=Chart().mark_line(color='blue').encode(x='x',y='y2') c
This produces the error:
AttributeErrorTraceback (most recent call last)
/home/nbuser/anaconda2_410/lib/python2.7/site-packages/IPython/core/formatters.pyc
in call(self, obj)
913 method = get_real_method(obj, self.print_method)
914 if method is not None:
--> 915 method()
916 return True
917

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc
in ipython_display(self)
443 from IPython.display import display
444 from vega import VegaLite
--> 445 display(VegaLite(self.to_dict(validate_columns=True)))
446
447 def display(self):

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc
in to_dict(self, data, validate_columns)
287 The JSON specification of the chart object.
288 """
--> 289 dct = super(TopLevelMixin, self.clone()).to_dict(data=data,
validate_columns=validate_columns)
290 dct['$schema'] = schema.vegalite_schema_url
291 return dct

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/
altair/v1/schema/_interface/jstraitlets.pyc in to_dict(self, kwargs)
151 def to_dict(self, *kwargs):
152 """Output a (nested) dict encoding the contents of this instance"""
--> 153 self._finalize(
kwargs)
154 Visitor = self._converter_registry.get('to_dict', ToDict)
155 return Visitor().visit(self, *
kwargs)

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc
in _finalize(self, **kwargs)
503 # and the Chart allows it.
504 if validate_columns and self.validate_columns:
--> 505 self._validate_columns()
506
507 def _finalize_data(self):

/home/nbuser/anaconda2_410/lib/python2.7/site-packages/altair/v1/api.pyc
in _validate_columns(self)
569 # Find columns with visual encodings
570 encoded_columns = set()
--> 571 encoding = self.encoding
572 if encoding is not jst.undefined:
573 for channel_name in encoding.channel_names:

AttributeError: 'LayeredChart' object has no attribute 'encoding'

Out[9]:


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/altair-viz/altair/issues/424, or mute the thread
https://github.com/notifications/unsubscribe-auth/AABr0DpVaIKRhrEPLotrDV4JNmsx5zflks5suqSbgaJpZM4QByO4
.

--
Brian E. Granger
Associate Professor of Physics and Data Science
Cal Poly State University, San Luis Obispo
@ellisonbg on Twitter and GitHub
[email protected] and [email protected]

You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub, or mute the thread.

I suggest temporal workaround :

import pandas as pd
import altair as alt
def pd2alt(df):
    return alt.Data(values = df.to_dict('records'))

df_stocks = alt.load_dataset( 'stocks')

# based on  'layer_line_color_rule.vl.json' from examples
chart = alt.LayeredChart(pd2alt(df_stocks),layers=[alt.Chart().mark_line().encode(
            color='symbol:N',
            x='date:T',
            y='price:Q',
        ), alt.Chart().mark_rule(
            opacity=0.5,
        ).encode(
            color='symbol:N',
            size=alt.Size(
                value=2.0,
            ),
            y='mean(price):Q',
        )])
chart

I don't know why but it doesn't work if you import atlair in the same cell as output chart.

I have just run into this problem, and it seems @iliatimofeev's fix doesn't work for me.

chart = alt.LayeredChart(mod_down_speeds, layers=[
    alt.Chart().mark_line().encode(
        x=alt.X('timestamp:T'),
        y=alt.Y('average(value)')
    ),
    alt.Chart().mark_line().encode(
        x=alt.X('timestamp:T'),
        y=alt.Y('median(value)')
    )])
chart

Error:

AttributeError                            Traceback (most recent call last)
~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
    916             method = get_real_method(obj, self.print_method)
    917             if method is not None:
--> 918                 method()
    919                 return True
    920 

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/api.py in _ipython_display_(self)
    443         from IPython.display import display
    444         from vega import VegaLite
--> 445         display(VegaLite(self.to_dict(validate_columns=True)))
    446 
    447     def display(self):

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/api.py in to_dict(self, data, validate_columns)
    287             The JSON specification of the chart object.
    288         """
--> 289         dct = super(TopLevelMixin, self.clone()).to_dict(data=data, validate_columns=validate_columns)
    290         dct['$schema'] = schema.vegalite_schema_url
    291         return dct

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/schema/_interface/jstraitlets.py in to_dict(self, **kwargs)
    151     def to_dict(self, **kwargs):
    152         """Output a (nested) dict encoding the contents of this instance"""
--> 153         self._finalize(**kwargs)
    154         Visitor = self._converter_registry.get('to_dict', ToDict)
    155         return Visitor().visit(self, **kwargs)

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/api.py in _finalize(self, **kwargs)
    503         # and the Chart allows it.
    504         if validate_columns and self.validate_columns:
--> 505             self._validate_columns()
    506 
    507     def _finalize_data(self):

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/api.py in _validate_columns(self)
    569             # Find columns with visual encodings
    570             encoded_columns = set()
--> 571             encoding = self.encoding
    572             if encoding is not jst.undefined:
    573                 for channel_name in encoding.channel_names:

AttributeError: 'LayeredChart' object has no attribute 'encoding'

I tried to use @iliatimofeev's pd2alt function, but get an error that timestamps are not JSON serializable.

My data looks like so:

timestamp measure value
0 2018-01-07 19:00:00 download 13.083797
1 2018-01-07 19:00:00 download 13.360251
2 2018-01-07 19:00:00 download 13.565831
3 2018-01-07 19:00:00 download 12.628750
4 2018-01-07 20:00:00 download 9.144189

Apologies if I'm overlooking a simple fix, but how would you suggest dealing with this? Is there another possible workaround, or should I clone the development version of Altair and use that?

I think it's another issue. My guess is that converting timestamp to
string (.astype(str)) before using altair will help. There is discussion on
prefered time format for vega somewhere in vega issues.

Вс, 11 марта 2018 г. в 21:15, Ethan Swan notifications@github.com:

I have just run into this problem, and it seems @iliatimofeev
https://github.com/iliatimofeev's fix doesn't work for me.

chart = alt.LayeredChart(mod_down_speeds, layers=[
alt.Chart().mark_line().encode(
x=alt.X('timestamp:T'),
y=alt.Y('average(value)')
),
alt.Chart().mark_line().encode(
x=alt.X('timestamp:T'),
y=alt.Y('median(value)')
)])
chart

Error:


AttributeError Traceback (most recent call last)
~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
916 method = get_real_method(obj, self.print_method)
917 if method is not None:
--> 918 method()
919 return True
920

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/api.py in _ipython_display_(self)
443 from IPython.display import display
444 from vega import VegaLite
--> 445 display(VegaLite(self.to_dict(validate_columns=True)))
446
447 def display(self):

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/api.py in to_dict(self, data, validate_columns)
287 The JSON specification of the chart object.
288 """
--> 289 dct = super(TopLevelMixin, self.clone()).to_dict(data=data, validate_columns=validate_columns)
290 dct['$schema'] = schema.vegalite_schema_url
291 return dct

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/schema/_interface/jstraitlets.py in to_dict(self, kwargs)
151 def to_dict(self, *kwargs):
152 """Output a (nested) dict encoding the contents of this instance"""
--> 153 self._finalize(
kwargs)
154 Visitor = self._converter_registry.get('to_dict', ToDict)
155 return Visitor().visit(self, *
kwargs)

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/api.py in _finalize(self, **kwargs)
503 # and the Chart allows it.
504 if validate_columns and self.validate_columns:
--> 505 self._validate_columns()
506
507 def _finalize_data(self):

~/anaconda3/envs/ad_hoc/lib/python3.6/site-packages/altair/v1/api.py in _validate_columns(self)
569 # Find columns with visual encodings
570 encoded_columns = set()
--> 571 encoding = self.encoding
572 if encoding is not jst.undefined:
573 for channel_name in encoding.channel_names:

AttributeError: 'LayeredChart' object has no attribute 'encoding'

I tried to use @iliatimofeev https://github.com/iliatimofeev's pd2alt
function, but get an error that timestamps are not JSON serializable.

My data looks like so:
timestamp measure value
0 2018-01-07 19:00:00 download 13.083797
1 2018-01-07 19:00:00 download 13.360251
2 2018-01-07 19:00:00 download 13.565831
3 2018-01-07 19:00:00 download 12.628750
4 2018-01-07 20:00:00 download 9.144189

Apologies if I'm overlooking a simple fix, but how would you suggest
dealing with this? Is there another possible workaround, or should I clone
the development version of Altair and use that?


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/altair-viz/altair/issues/424#issuecomment-372136263,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ALBqbVsmt6a3CYwcTO17-bu6lAxTMAHhks5tdWnOgaJpZM4QByO4
.

Could you try the Vega-Lite 2 stuff in master? The Layered chart support there is much better.

Fixed in v2

It seems like the issue persists in v2, unless I am missing something here.
alt.__version__
'2.1.0'

import altair as alt

slope = 2.0
sigma = 0.33

x_train = np.linspace(-1, 1, 11)
y_train = (slope * x_train) + (sigma * np.random.randn(*x_train.shape))
y_learned = np.polyval(np.polyfit(x_train, y_train, 1), x_train)

kx = 'training x'
ky = 'training y'
kl = 'learned y'

points = alt.Chart(df).mark_circle().encode(x=kx, y=ky)
lines  = alt.Chart(df).mark_line().encode(x=kx, y=kl)

points.display() # no problem
lines.display()  # no problem
alt.LayeredChart(df, layer=[points, lines])
AttributeError: module 'altair' has no attribute 'LayeredChart'

alt.layer(points, lines, data = df) will work.
Altair 2.0.1 has totally new syntax for layered charts as vega-lite 2 do. Please check documentation on compound charts.

Hi there, many thanks for Altair, it's been great so far.
Unfortunately I believe this (or a similar) issue persists as, for example, the Vertical Concatenation example doesn't seem to work in version 2.0.1: AttributeError: 'Chart' object has no attribute 'add_selection'. Cheers.

The add_selection method was added in Altair version 2.1. If you update Altair, it should work.

Was this page helpful?
0 / 5 - 0 ratings