Giter VIP home page Giter VIP logo

ipyvega's Introduction

Vega: A Visualization Grammar

Vega Examples

Vega is a visualization grammar, a declarative format for creating, saving, and sharing interactive visualization designs. With Vega you can describe data visualizations in a JSON format, and generate interactive views using either HTML5 Canvas or SVG.

For documentation, tutorials, and examples, see the Vega website. For a description of changes between Vega 2 and later versions, please refer to the Vega Porting Guide.

Build Instructions

For a basic setup allowing you to build Vega and run examples:

  • Clone https://github.com/vega/vega.
  • Run yarn to install dependencies for all packages. If you don't have yarn installed, see https://yarnpkg.com/en/docs/install. We use Yarn workspaces to manage multiple packages within this monorepo.
  • Once installation is complete, run yarn test to run test cases, or run yarn build to build output files for all packages.
  • After running either yarn test or yarn build, run yarn serve to launch a local web server โ€” your default browser will open and you can browse to the "test" folder to view test specifications.

This repository includes the Vega website and documentation in the docs folder. To launch the website locally, first run bundle install in the docs folder to install the necessary Jekyll libraries. Afterwards, use yarn docs to build the documentation and launch a local webserver. After launching, you can open http://127.0.0.1:4000/vega/ to see the website.

Internet Explorer Support

For backwards compatibility, Vega includes a babel-ified IE-compatible version of the code in the packages/vega/build-es5 directory. Older browser would also require several polyfill libraries:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.4.4/polyfill.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/runtime.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/fetch.umd.min.js"></script>

Contributions, Development, and Support

Interested in contributing to Vega? Please see our contribution and development guidelines, subject to our code of conduct.

Looking for support, or interested in sharing examples and tips? Post to the Vega discussion forum or join the Vega slack organization! We also have examples available as Observable notebooks.

If you're curious about system performance, see some in-browser benchmarks. Read about future plans in our roadmap.

ipyvega's People

Contributors

brettcannon avatar chmp avatar cpsievert avatar cscheid avatar dependabot-preview[bot] avatar dependabot[bot] avatar domoritz avatar ellisonbg avatar jakevdp avatar jdfekete avatar maartenbreddels avatar stonebig avatar tjni avatar toddrme2178 avatar xtianpoli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ipyvega's Issues

Update the README

I haven't looked, but after #32 is merged, we should probably update the README:

  • Provide links to the demo notebooks on GitHub and nbviewer.
  • Start to promote that it works on GitHub and nbviewer.
  • Audit the installation and dev instructions.
  • Update screenshots for vega+vegalite.

Note vega and vegalite versions at the Python level

I think it would be useful to have the versions of the javascript packages available at some level, e.g.

from vega import VegaLite
print(VegaLite.library_version)

This would facilitate, e.g. raising a warning in Altair if someone has incompatible versions installed.

Allow ``VegaLite`` to accept either dict or JSON string?

This came up in our chat โ€“ I think it's a good idea.

Could look something like this:

class Vegalite(object):
    def __init__(self, spec):
        try:
            spec = json.loads(spec)
        except TypeError:
            pass
        if 'data' not in spec:
            raise KeyError('No data provided with spec')
        self.spec = utils.update(spec, DEFAULTS, overwrite=False)

Advantage is more flexible API & ability to out-source dataframe formatting stuff to Pandas; the disadvantage is that in some situations we'd add an extra string->dict->string cycle.

Vega lite integration

Call this way:

from vega import vegalite
vegalite.display(spec)

Then display the visualization.

use case: vincent replacement, using python

Per Dominik's request, I'm attaching my use case, and hope to work with the authors to make this use case work.

My workflow is simulation -> JSON -> pandas -> ? -> vega. Currently the ? is vincent, but vincent is not Vega-2.0-compliant and the author, who did a great job on it, isn't currently maintaining it. My simulation generates a lot of data; pandas is exactly the right tool (in python) for slicing and dicing that data; my hope is this package will fill in the ? where vincent is currently kind-of doing the job.

I am less interested in the ipython case and more interested in just using plain python as a batch script, but I think I will try out ipython since that is a design goal for y'all. I will also have suggestions on how to write good docs/examples that make it easy for others to use your tool. (This is a place where vincent could improve. What I will suggest is that for a given plot type, you explicitly say what it expects as an argument in terms of a pandas DataFrame, for instance, "GroupedBar: expects a pandas DataFrame where the rows are a set of measurements that are grouped together (in the GroupedBar 'group'), and each column is one individual measurement").

It is also my hope that I can generate both web plots (via D3, in the web browser) as well as print plots (SVG, PDF, etc.).

Thanks for writing this!

VegaLite erroneously requires data to be specified at the top level

The following spec should produce a valid plot, and does when converted to JSON and fed to vega-lite directly:

spec = {'layers': [{'config': {'mark': {'color': '#1f77b4'}},
   'data': {'values': [{'x': 0, 'y': 0}, {'x': 1, 'y': 1}]},
   'encoding': {'x': {'field': 'x', 'type': 'quantitative'},
    'y': {'field': 'y', 'type': 'quantitative'}},
   'mark': 'line'},
  {'config': {'mark': {'color': '#ff7f0e'}},
   'data': {'values': [{'x': 0, 'y': 1}, {'x': 1, 'y': 0}]},
   'encoding': {'x': {'field': 'x', 'type': 'quantitative'},
    'y': {'field': 'y', 'type': 'quantitative'}},
   'mark': 'point'}]}

When used with this package, though, it results in an error:

from vega import VegaLite
VegaLite(spec)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-25-9af8065cc04d> in <module>()
      1 from vega import VegaLite
----> 2 VegaLite(spec)

/Users/jakevdp/anaconda/lib/python3.5/site-packages/vega/base.py in __init__(self, spec, data)
     21         """Initialize the visualization object."""
     22         spec = utils.nested_update(copy.deepcopy(self.DEFAULTS), spec)
---> 23         self.spec = self._prepare_spec(spec, data)
     24 
     25     def _prepare_spec(self, spec, data):

/Users/jakevdp/anaconda/lib/python3.5/site-packages/vega/vegalite.py in _prepare_spec(self, spec, data)
     22 
     23     def _prepare_spec(self, spec, data):
---> 24         return prepare_spec(spec, data)
     25 
     26 

/Users/jakevdp/anaconda/lib/python3.5/site-packages/vega/utils.py in prepare_spec(spec, data)
     91         # Data is either passed in spec or error
     92         if 'data' not in spec:
---> 93             raise ValueError('No data provided')
     94     else:
     95         # As a last resort try to pass the data to a DataFrame and use it

ValueError: No data provided

Currently the package assumes that data must appear at the top level; with the new Layer options, this is no longer strictly required.

Bug: jupyter nbextension install attempts to create directories outside virtualenv

The following installation step

jupyter nbextension install --py vega

fails when run inside virtualenv while attempting to modify global distribution directories

(mcmc)madanh@madanh ~/.virtualenvs/mcmc $ jupyter nbextension install --py vega
Installing /home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/vega/static -> jupyter-vega
Traceback (most recent call last):
  File "/home/madanh/.virtualenvs/mcmc/bin/jupyter-nbextension", line 11, in <module>
    sys.exit(main())
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/jupyter_core/application.py", line 267, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/notebook/nbextensions.py", line 900, in start
    super(NBExtensionApp, self).start()
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/jupyter_core/application.py", line 256, in start
    self.subapp.start()
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/notebook/nbextensions.py", line 678, in start
    self.install_extensions()
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/notebook/nbextensions.py", line 657, in install_extensions
    **kwargs
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/notebook/nbextensions.py", line 225, in install_nbextension_python
    destination=dest, logger=logger
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/notebook/nbextensions.py", line 126, in install_nbextension
    ensure_dir_exists(nbext)
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/site-packages/ipython_genutils/path.py", line 167, in ensure_dir_exists
    os.makedirs(path, mode=mode)
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/os.py", line 227, in makedirs
    makedirs(head, mode, exist_ok)
  File "/home/madanh/.virtualenvs/mcmc/lib/python3.4/os.py", line 237, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/usr/local/share/jupyter'

Python 3 support?

I might be doing something wrong here, but I couldn't import vega using Python 3.5.

ImportError                               Traceback (most recent call last)
<ipython-input-1-4f3fd77079e7> in <module>()
----> 1 import vega

/.../lib/python3.5/site-packages/vega/__init__.py in <module>()
----> 1 import tool
      2 import polestar
      3 import voyager
      4 import vegalite

ImportError: No module named 'tool'

Does it currently support only Python 2? Relative imports don't work like that in Python 3, if I remember correctly, you'd need to use import .tool. I can try to work on a Python 3 patch if needed. Any thoughts?

Allow PNG-only mode

Because many python-generated vega plots result in data being embedded into the notebook, notebook size can quickly grow beyond what the browser can handle (see altair-viz/altair#249). Would there be a way to optionally enable PNG-only mode, where on save (or perhaps on render) the live output is replaced by the PNG and removed? I think the JS could be tweaked to do this, but it's not clear to me how this could be easily enabled/disabled from the Python side.

cc/ @ellisonbg

Print supresses display of vega-lite figure

I've encounterd a problem with pyvega and the Python print function.
The following example works, hence the figure is displayed correctly in the notebook:

import altair
altair.Chart(altair.load_dataset('movies')).encode(x='Production_Budget', y='IMDB_Rating')

If I print anything in this same cell, the figure output disappears:

import altair
print('foo')
altair.Chart(altair.load_dataset('movies')).encode(x='Production_Budget', y='IMDB_Rating')

Is this expected behavior?
Niels

stacked area chart not rendering correctly via VegaLite.display()

The test case below works fine on http://vega.github.io/vega-editor/?mode=vega-lite but not in a notebook on a freshly built checkout of origin/master. Specifically, the larger of the two areas draws without normalization.

--------------- test case ----------
from vega import VegaLite
data = [
    {'count': 1532, 'date': '2016-07-05', 'label': 'group2'},
    {'count': 4712, 'date': '2016-07-05', 'label': 'group1'},
    {'count': 1736, 'date': '2016-07-06', 'label': 'group2'},
    {'count': 4970, 'date': '2016-07-06', 'label': 'group1'},
    {'count': 1960, 'date': '2016-07-07', 'label': 'group2'},
    {'count': 5248, 'date': '2016-07-07', 'label': 'group1'},
    {'count': 2002, 'date': '2016-07-08', 'label': 'group2'},
    {'count': 5360, 'date': '2016-07-08', 'label': 'group1'},
    {'count': 1969, 'date': '2016-07-09', 'label': 'group2'},
    {'count': 4548, 'date': '2016-07-09', 'label': 'group1'},
    {'count': 1931, 'date': '2016-07-10', 'label': 'group2'},
    {'count': 4631, 'date': '2016-07-10', 'label': 'group1'},
    {'count': 2316, 'date': '2016-07-11', 'label': 'group2'},
    {'count': 5817, 'date': '2016-07-11', 'label': 'group1'}]
graphic = {
    "mark": "area",
    "encoding": {
        "y": {"aggregate": "sum", "field": "count", "type": "quantitative"},
        "x": {"field": "date", "type": "temporal"},
    "color": {"field":"label", "type":"nominal", "scale": {"range": ["#e6aa06", "#1f77b4"]}}
    },
    "config": {"mark": {"stacked": "normalize"}}
}
VegaLite(graphic, data).display()
-----------------

Cannot configure vl width

It seems like the config cannot be overridden.

VegaLite({
  "mark": "point",
  "encoding": {
    "y": {"type": "quantitative","field": "Acceleration"},
    "x": {"type": "quantitative","field": "Horsepower"},
    "color": {"type": "nominal","field": "Origin"}
  },
  "config": {
    "cell": {
      "width": 100
    }
  }
}, df)

Export VL chart

When you are done with your exploration, you probably want to have a visualization in a separate cell. We should make this process simple.

Release script

  • change the version numbers in the package.json, index.py
  • tag a version
  • push to pypi and conda

Enable copying PNG more easily

I end up sharing a lot of rendered graphs on Slack which has the handy ability to upload images from the clipboard. With matplotlib visualizations there's a vanilla rendered that I can right-click and say 'copy image' and then just paste it into slack which works great. However with vega I have to add the intermediate step of saving the graph as a png first which really slows things down.

I was wondering if it might be possible to add another option beside "Export as PNG" like "Copy as PNG" that would do the same operation but plop the results in the clipboard?

Persistent spec

Store the vl spec from polestar in the notebook file and load it if it is present.

Document how to update JS dependencies

I gather that something reads package.json and then updates index.js/index.js.map. We need the commands that do this to be documented somewhere in the package (perhaps in the README?)

Serve data from server extension

Instead of embedding the data as serialized json in the notebook, the data should be served from the kernel (through a server extension) if that's possible.

@ellisonbg could you tell us whether this is possible and how we roughly would go about this?

"nbconvert"ed interactive Vega plots

Using the nbconvert tool, it would be nice be able to export notebooks containing Vega plots in html (and rst) format. For static plots it just works, but for good reasons all the interactive features of a plot disappear. Links to the d3 and vega javascript libraries need to be added to the HTML template that is passed to nbconvert, and some magic to preserve the plot specification also need to happen in the preprocessing and conversion steps.

Are you able to offer advice on how to write such magic? By calling the private functions _generate_html and _generate_js on the vega.vega.Vega object I can get the relevant snippets of code, but my knowledge about Jupyter and nbconvert is not deep enough to understand how I can make them survive through to the output HTML.

Rename to ipython-vega

Consistent repo name, package name, folder names.

Repo name should be ipython-vega, all other names should be vega.

vega.vegalite
vega.polestar
vega.voyager

Refactor to use Jupyter's custom MIME type based rendering

In JupyterLab we are moving to rendering custom outputs using custom MIME types and functions that get registered to rendering those MIME types. I have that working well for JupyterLab, and am working on a version for the classic notebook. This will dramatically simplify the code base and lead to only the actual vega/vegalite JSON spec being stored in the notebook (rather than a bunch of JS code). Will also enable us to get these things working on nbviewer.

This will result in a complete refactor of basically everyfile in this repo...can I hold the lock for a few days?

@domoritz @jakevdp

Polestar with notebook configuration

I think the easiest integration of polestar with IPython notebooks is to have a configuration that disables the dataset selector and somehow listens to data changes from the kernel. We should implement a postMessage like interface. regardless, we have to make sure that we keep things contained so it works in jupyter and colab.

Installation failure

When performing a conda install, I'm seeing the following. Any thoughts on what might be going wrong?

% conda install vega --channel conda-forge
Fetching package metadata .........
Solving package specifications: ..........

Package plan for installation in environment /Users/cpd/anaconda/envs/defaultenv:

The following NEW packages will be INSTALLED:

    vega: 0.4.2-py27_1 conda-forge

Proceed ([y]/n)?

Linking packages ...
Install Jupyter notebook extensions

Usage

    jupyter nbextension install path/url

This copies a file or a folder into the Jupyter nbextensions directory. If a URL
is given, it will be downloaded. If an archive is given, it will be extracted
into nbextensions. If the requested files are already up to date, no action is
taken unless --overwrite is specified.

Options
-------

Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.

--quiet
    Minimal output
--symlink
    Create symlink instead of copying files
-s
    Create symlink instead of copying files
--user
    Install to the user's IPython directory
--debug
    Extra output
--overwrite
    Force overwrite of existing files
--prefix=<Unicode> (InstallNBExtensionApp.prefix)
    Default: ''
    Installation prefix
--destination=<Unicode> (InstallNBExtensionApp.destination)
    Default: ''
    Destination for the copy or symlink
--nbextensions=<Unicode> (InstallNBExtensionApp.nbextensions_dir)
    Default: ''
    Full path to nbextensions dir (probably use prefix or user)

To see all available configurables, use `--help-all`

Examples
--------

    jupyter nbextension install /path/to/myextension

[InstallNBExtensionApp] CRITICAL | Bad config encountered during initialization:
[InstallNBExtensionApp] CRITICAL | Unrecognized flag: '--py'
Error: Error: post-link failed for: conda-forge::vega-0.4.2-py27_1

Implement vincent functionalities

https://github.com/wrobstory/vincent is a python to vega translator. We should have a simple way for users to create a vl visualizations from an ipython notebook.

Something like

import vega
vega.vegalite.create({
{
  "marktype": "point",
  "encoding": {
    "x": {"name": "Acceleration","type": "Q"},
    "y": {"name": "Horsepower","type": "Q"},
  }
}
})

Static PNG render of vegalite

For vegalite visualizations to be seen on sites like nbviewer or github, we need to have static PNG versions of them embedded into the notebooks output. It looks like it is possible to get a base64 encoded PNG from the SVG on the page. Then we would just need to use the output area JS API to put that into the cell. I will try to get an example working that does something like this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.