altair-viz / altair_viewer Goto Github PK
View Code? Open in Web Editor NEWViewer for Altair and Vega-Lite visualizations
License: BSD 3-Clause "New" or "Revised" License
Viewer for Altair and Vega-Lite visualizations
License: BSD 3-Clause "New" or "Revised" License
This simple code crashes: save(chart_with_labels, "chart.png")
With this error:
NoMatchingVersions: No matches for version='5.8.0' among ['4.0.2', '4.8.1', '4.17.0']. Often this can be fixed by updating altair_viewer: pip install -U altair_viewer
Trying to update altair_viewer doesn't help. What's wrong?
Newest version 0.4.0 does not include vega-lite version 5.2.0 in its listing.json
file.
This has a cascading effect and generates an error when trying to build documentation on the altair repo (I actually discovered this whilst addressing #2645).
Just run make html
under the doc directory, having all requirements installed via pip.
Error message:
exception: No matches for version='5.2.0' among ['4.0.2', '4.8.1', '4.17.0'].
Often this can be fixed by updating altair_viewer: pip install -U altair_viewer
This, however, does not fix the problem.
Taking a look at the logs, altair_viewer
's latest version was published on November 2021, while the listing.json
file was updated on January 2022. If I'm not terribly mistaken, republishing the package would fix this problem.
I recently had to update altair to master to address an unrelated issue, and found that altair_viewer
's registration no longer worked. Might need to update the entrypoints to something like
https://github.com/vega/ipyvega/blob/e7fb07ce599f78117b94bcaeddd8dc56e5554a38/pyproject.toml#L40
line1 = alt.Chart(Data).mark_line().encode(
x='mean(Value)',
y='Profondeur',
color='Type')
line1
Traceback (most recent call last):
File C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\formatters.py:974 in call
return method(include=include, exclude=exclude)
File C:\ProgramData\Anaconda3\lib\site-packages\altair\vegalite\v5\api.py:2161 in repr_mimebundle
return renderers.get()(dct)
File C:\ProgramData\Anaconda3\lib\site-packages\altair_viewer_viewer.py:323 in render
out = self.display(
File C:\ProgramData\Anaconda3\lib\site-packages\altair_viewer_viewer.py:268 in display
raise RuntimeError("Internal: _stream is not defined.")
RuntimeError: Internal: _stream is not defined.
Charts are served to the Viewer via a background service implemented on Tornado.
On Windows 10, Python 3.8, Tornado won't start. This may apply to more Altair renderers than 'altair_viewer' and 'mimetype'. I am working outside a notebook environment (Jupyter, Collab, etc). Without Tornado, display() and show() don't work. Practically speaking, it looks like the best work around for a non notebook IDE or user around is to render charts to html (Chart.save()).
The stack trace points to asyncio,
asyncio\events.py", line 501, in add_reader raise NotImplementedError
This stackoverflow thread points a platform constraint:
https://stackoverflow.com/questions/54608421/how-to-fix-notimplementederror-when-trying-to-run-hydrogen-in-atom
If I am understanding the issue and workaround correctly, it might be worth mentioning in the doc, at https://altair-viz.github.io/user_guide/display_frontends.html#altair-viewer
altair.Chart
works with a dataframe, but not with a JSON file. I get a
WARNING:tornado.access:404 GET /dat.json (127.0.0.1) 0.37ms
.
Here is a minimal example:
import pandas as pd
import altair
altair.renderers.enable("altair_viewer")
df = pd.DataFrame({"year": [1, 2, 3], "height": [120, 130, 140]})
df.to_json("dat.json", orient="records")
chart = (
altair.Chart(df)
.mark_line()
.encode(
x="year:O",
y="height:Q",
)
)
chart2 = (
altair.Chart("dat.json")
.mark_line()
.encode(
x="year:O",
y="height:Q",
)
)
I ran it with ipython
then %run mwe.py
, then just chart2
to display the chart in a browser tab. However, the chart is empty and I get the 404 error described above.
I was giving the new package a try and was unsure about some behavior.
When running in an Ipython session each call to display
opened up a new window/tab. Is that expected? I was thinking subsequent calls would just refresh the window rather than open a new tab.
import altair as alt
from vega_datasets import data
import altair_viewer
source = data.iris()
chart = alt.Chart(source).mark_circle().encode(
alt.X('sepalLength', scale=alt.Scale(zero=False)),
alt.Y('sepalWidth', scale=alt.Scale(zero=False, padding=1)),
color='species',
size='petalWidth'
)
altair_viewer.display(chart)
altair_viewer.display(chart)
This is not really an issue, just sharing something that might be useful to others. I found this one of the tricker barriers to using Altair in a way that worked for me. If this is a common enough use case maybe it could be added to the package.
My use case:
For this, I create the chart HTML with chart.to_html()
then inject a script to reload the file when it's updated:
html = chart.to_html().replace(
"</body>",
"""<script type='text/javascript'>
const POLL_INTERVAL = 1000
const fetchLastModified = () => fetch(document.location, {method: 'HEAD'})
.then(res => res.headers.get('last-modified'))
fetchLastModified().then(lastModified => {
setInterval(() => {
if (document.hidden) return
fetchLastModified().then(lastModified2 => {
if (lastModified !== lastModified2) document.location.reload()
})
}, POLL_INTERVAL)
})
</script>
</body>
""",
)
The script checks every second for a new version of the file. It only does this while the browser window is visible, and makes a HEAD
request which is tiny (even so, probably not suitable for anything but local serving).
Then I save this to disk with the chart name and print a link to open it (once per session).
I serve the file with a static web server (PyCharm has http://localhost:63342 always running, others could use py -m http.server
).
Hello,
I have been using Altair for a few years, but now having trouble launching the altair_viewer where I am getting the following error message:
altair.utils.schemapi.SchemaValidationError: VConcatChart
has no parameter named 'selection'
My code is shown below. It is on the newer installations of Altair where I have a problem, so I am guessing my code is out of date.
`#from pandas import DataFrame, read_csv
from pandas import DataFrame
import altair as alt
import altair_viewer
#alt.renderers.enable('altair_viewer')
import altair_transform
alt.data_transformers.disable_max_rows()
import pandas as pd
import numpy as np
import geolog
while geolog.gettable():
df=pd.DataFrame({'wells':wells,'date':date,'bopm':bopm,'bwpm':bwpm,'xx_bottom':xx_bottom,'yy_bottom':yy_bottom,'wor':wor,'wcut':wcut,'lwcut':lwcut,'lwor':lwor})
interval = alt.selection_interval()
base = alt.Chart(df).properties(
width=1000,
height=1000,
).add_params(interval)
points = base.mark_point(filled=True).encode(
x='xx_bottom:Q',
y='yy_bottom:Q',
size='bopm:Q',
#color=alt.condition(interval, 'wells', alt.value('lightgray')),
color=alt.condition(interval, 'wells', alt.value('lightgray')),
tooltip='wells',
).properties(
title='Field Map, Wells Sized by BOPM',
selection=interval
)
timeseries = base.mark_line(clip=False).encode(
x='date:T',
#alt.X('date:T', timeUnit='year', axis=alt.Axis(title='')),
y='sum(bopm):Q',
#y=alt.Y('sum(bopm):Q', scale=alt.Scale(domain=(0, 10000000000))),
#color=alt.Color('wells:O')
color=alt.value('green'),
tooltip='date:T'
).properties(
title='Production by Well in BOPM',
width=450,
height=300,
#selection=interval
).transform_filter(
#title='Volve Field BOPD',
interval
)
timeseries2 = base.mark_line(clip=False).encode(
x='date:T',
#alt.X('date:T', timeUnit='year', axis=alt.Axis(title='')),
y='sum(bwpm):Q',
#y=alt.Y('sum(bwpm):Q', scale=alt.Scale(domain=(0, 10000000000))),
#color=alt.Color('wells:O')
color=alt.value('blue'),
tooltip='date:T',
).properties(
title='Production by Well in BWPM',
width=450,
height=300,
#selection=interval
).transform_filter(
#title='Volve Field BOPD',
interval
)
histd = alt.Chart(df).mark_line().encode(
x='date:T',
#alt.X('date:T', timeUnit='year', axis=alt.Axis(title='')),
y='median(lwcut):Q',
#alt.Y('mean(wcut)', scale=alt.Scale(type='log', base=10, domain=(0.001, 1.0)), axis=alt.Axis(orient='left') ),
color=alt.value('blue'),
#color='wells'
#tooltip='date:T',
).properties(
width=1000,
height=300
).transform_filter(
interval
)
histcum = alt.Chart(df).mark_line().encode(
x='bopm:Q',
#alt.X('date:T', timeUnit='year', axis=alt.Axis(title='')),
y='median(lwcut):Q',
#alt.Y('mean(wcut)', scale=alt.Scale(type='log', base=10, domain=(0.001, 1.0)), axis=alt.Axis(orient='left') ),
color=alt.value('blue'),
#color='wells'
#tooltip='date:T',
).properties(
width=1000,
height=300
).transform_filter(
interval
)
histcum2 = alt.Chart(df).mark_line().encode(
#x='bopm:Q',
alt.X('bopm:Q', axis=alt.Axis(title='')),
#y='median(lwcut):Q',
alt.Y('mean(wcut)', scale=alt.Scale(type='log', base=10, domain=(0.00001, 1.0)), axis=alt.Axis(orient='left') ),
color=alt.value('blue'),
#color='wells'
#tooltip='date:T',
).properties(
width=1000,
height=300
).transform_filter(
interval
)
first = points
second = timeseries | timeseries2
third = histd
forth = histcum
#points & timeseries & timeseries2 & bhp & hist & hist2 & hist3
plot=first & second & third & forth
#plot.show()
altair_viewer.show(plot)
# Store data into geolog
geolog.puttable()
`
Hello. I run Altair from Docker container, and I would like to see a plot with my Host machine's browser. In order to do it I execute a code like below:
df=... # my data
alt.Chart(df).mark_line().encode(x='step', y='value').show()
The code prints a notice like Displaying chart at http://localhost:15169/
.
Unfortunately, if I open the browser and point it to 172.17.0.4:15169
(It happens to be my container's ip) I only see Altair favicon but no plots. This is because HTML contains urls that refer to server as to localhost
, which has meaning only inside the container. Is it possible to explicitly specify the IP to bind to?
(There is a workaround - to create custom viewer with viewer=ChartViewer(use_bundled_js=False)
and use it, but I would still like to get scripts installed on my container machine.)
When running
import pandas as pd
import altair as alt
import mid_utils as mu
import altair_viewer
alt.renderers.enable('altair_viewer')
...
...
baz = alt.Chart(bar).mark_bar().encode(x='upper', y='Häufigkeit', color='HVM:N')
altair_viewer.display(baz)
in IPython (within Pycharm) I get the following exception:
Exception in thread Thread-21:
Traceback (most recent call last):
File "D:\miniconda\envs\mid17_schemes\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "D:\miniconda\envs\mid17_schemes\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "D:\miniconda\envs\mid17_schemes\lib\site-packages\altair_data_server\_background_server.py", line 66, in start_server
httpd.listen(port=port, address=address)
File "D:\miniconda\envs\mid17_schemes\lib\site-packages\tornado\tcpserver.py", line 152, in listen
self.add_sockets(sockets)
File "D:\miniconda\envs\mid17_schemes\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
self._handlers[sock.fileno()] = add_accept_handler(
File "D:\miniconda\envs\mid17_schemes\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
io_loop.add_handler(sock, accept_handler, IOLoop.READ)
File "D:\miniconda\envs\mid17_schemes\lib\site-packages\tornado\platform\asyncio.py", line 100, in add_handler
self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
File "D:\miniconda\envs\mid17_schemes\lib\asyncio\events.py", line 501, in add_reader
raise NotImplementedError
NotImplementedError
Installed versions:
altair | 4.1.0 |
altair_data_server | 0.4.1 |
altair_viewer | 0.3.0 |
Do I something wrong or is this a bug with IPython/Pycharm?
When a large altair chart is displayed in the browser (large = a fair bit larger than your browser window), it is truncated.
Minimal example:
import altair as alt
import numpy as np
import pandas as pd
df = pd.DataFrame(dict(x=np.linspace(0, 1, 100), y=np.random.random(100)))
chart = alt.Chart(df, width=5000, height=5000).mark_line().encode(x="x", y="y")
chart.show()
When I open this in Firefox or Safari (both on Mac), I see approximately the bottom half and left two thirds of the chart. I cannot scroll to the top-left corner. Zooming out in the browser renders the whole chart (in Firefox), but that's not a usable work-around.
This seems to be caused by the properties of the chart's enclosing div
(lines 23-26 in _viewer.py
, version 0.3.0):
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
That's nice for showing a small chart centered, but it seems to break the display of very large charts. Removing that code (or deleting the respective properties in the Firefox dev tools) solves the issue.
My suggested solution would be to make this configurable either with a switch center_chart
that includes or does not include the above CSS, or by adding an option to supply custom CSS for the chart's enclosing div
and the above CSS being the default. What do you think? I'd be happy to take a shot at fixing this.
Actually, it would probably be much nicer to find a bit of CSS that works regardless of the chart size and hard-code that in the template. Who wants to remember that fixing a truncated chart requires fiddling with the template CSS...
(Edited: changed my mind about the suggested solution :) )
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.