Package: canvasxpress
CanvasXpress Python LibraryAbout CanvasXpress for PythonCanvasXpresswas developed as the core visualization component for bioinformatics
and systems biology analysis at Bristol-Myers Squibb. It supports a large number
ofvisualizationsto display scientific and non-scientific data.CanvasXpressalso includes a simple and unobtrusiveuser interfaceto explore complex data sets, a sophisticated and
unique mechanism to keep track of all user customization forReproducible Researchpurposes, as well as an 'out of the box'
broadcasting capability to synchronize selected data points across allCanvasXpressplots in a page. Data can be
easily sorted, grouped, transposed, transformed or clustered dynamically. The fully customizable mouse events as well as
the zooming, panning and drag-and-drop capabilities are features that make this library unique in its class.CanvasXpresscan be now be used within Python for native integration into IPython and Web environments, such as:StreamlitPlotly DashJupyterFlaskDjangoComplete examples using theCanvasXpresslibrary including the mouse events, zooming, and broadcasting
capabilities are included in this package. ThisCanvasXpressPython package was created by Dr. Todd C. Brett, with support fromAggregate Genius Inc., in cooperation with theCanvasXpressteam.The maintainer of the Python edition of this package isDr. Todd C. Brett.Project StatusTopicStatusReleasePythonEditionPopularityBuildCoverageCodeEnhancementsStreamlit Dashboards are now supported!🥳 🎉Streamlit is a popular dashboard framework that is generally simpler to use than Plotly Dash or Shiny for Python, but
just as powerful in terms of extensions and reactivity.Jupyter Notebook exports are now supported!Rendering in Notebooks has been available since Day 1, but now exporting saved notebooks to PDF, HTML, and other formats
is supported!  The HTML export includesliveCanvasXpress charts, which makes this an excellent option for
distributing rendered materials on the Web or with colleagues unfamiliar with notebook functionality.Pinned CanvasXpress versions are now supported!To facilitate productin and reproducible research environments, the edition of CanvasXpress to be used can now be set.
For example, version34.9. By default the latest available edition of CanvasXpress will be used.A complete list of enhancements by release date is available at theCanvasXpress for Python Status Page.Known IssuesNoneRoadmapThis package is actively maintained and developed. Our focus for 2023 is:Immediate FocusUpdated and detailed documentation and working examples of all Python functionalityShiny for Python supportGeneral FocusIntegraton with dashboard frameworks for easier applet creationContinued alignment with the CanvasXpress Javascript libraryContinued stability and security, if/as neededGetting StartedDocumentationThedocumentation sitecontains completeexamplesandAPI documentation. There is also a wealth of additional
information, including full Javascript API documentation,
athttps://www.canvasxpress.org.Note: We will begin replacing readthedocs with Quarto based examples this year.**
New:**Jupyter Notebook based examplesfor hundreds of chart configurations!InstallationCanvasXpress for Python can be installed usingpip:The essential CanvasXpress package, for use with the CLI or flask and similar environments, can be installed using:pip install canvasxpressorpip install "canvasxpress[core]"Jupyter components can be additionally installed with the core package via:pip install "canvasxpress[jupyter]"Dash components can be additionally installed as:pip install "canvasxpress[dash]"And Streamlit components can be additionally installed as:pip install "canvasxpress[streamlit]"To get everything in one installation use:pip install "canvasxpress[all]"A Quick Script/Console ExampleCharts can be defined in scripts or a console session and then displayed using the default browser, assuming that a
graphical browser with Javascript support is available on the host system.fromcanvasxpress.canvasimportCanvasXpressfromcanvasxpress.render.popupimportCXBrowserPopupif__name__=="__main__":# Define a CX bar chart with some basic datachart:CanvasXpress=CanvasXpress(data={"y":{"vars":["Gene1"],"smps":["Smp1","Smp2","Smp3"],"data":[[10,35,88]]}},config={"graphType":"Bar"})# Display the chart in its own Web pagebrowser=CXBrowserPopup(chart)browser.render()Upon running the example the following chart will be displayed on systems such as MacOS X, Windows, and Linux with
graphical systems:A Quick Streamlit ExampleStreamlitis a popular dashboard framework that is simplified compared to Dash and Shiny, but
just as powerful in terms of reactivity and extensions. This example shows how to create a basic Streamlit application
using a CanvasXpress Streamlit element.A basic Streamlit app provides a means by which:A local development server can be startedA function can respond to a URLFirst install Streamlit and CanvasXpress for Python:pip install streamlit
pip install canvasxpress[streamlit]Then create a demo file, such asapp.py, and insert:importrandomimportstreamlitasstfromcanvasxpress.canvasimportCanvasXpressfromcanvasxpress.renderimportstreamlitascx_st# A basic bar chart.  It's anonymous, so no render_to.  Data is added during the draw phase.chord_chart=CanvasXpress(config={"graphOrientation":"vertical","plotBox":True,"showLegend":False,"smpLabelRotate":90,"smpTitle":"Samples","theme":"CanvasXpress","title":"Bar Graph Title","xAxis":["V1"],"xAxisTitle":"Value","graphType":"Bar"},width=500,height=500)# Write the UI to the browser# This code will be re-executed with each click of the button# Name the themest.title('CanvasXpress in Streamlit!')# Some columns to organize the button and chartcolumn1,column2=st.columns(2)# A column with our data generator buttoncolumn1.write(# This has no associated action, so by default it triggers a redraw of the UI.st.button("Generate New Data"))# Another column with the chart displayed# With each redraw generate new random valueschord_chart.data={"y":{"vars":["V1"],"smps":["S1","S2","S3"],"data":[[random.randint(100,10000),random.randint(100,10000),random.randint(100,10000),]]}}column2.write(# This plots the CanvasXpress chart into the UI.cx_st.plot(chord_chart))Run the App and View the PageOn the command line, execute:streamlit run app.pyAnd output similar to the following will be provided:Running on http://localhost:8501/ (Press CTRL+C to quit)Browsing tohttp://localhost:8501/will result in a page with a CanvasXpress chart, which is being hosted by the
Streamlit framework:Congratulations!  You have created a Streamlit CanvasXpress app!A Quick Dash ExamplePlotly Dashis a popular dashboard framework similar to R/shiny for Python. Dash
applications are Web pages with widgets and elements facilitating the interactive presentation of information. This
example shows how to create a basic Dash application using a CanvasXpress Dash element.Create a Basic Dash AppA basic Dash app provides a means by which:A local development server can be startedA function can respond to a URLFirst install Dash and CanvasXpress for Python:pip install dash
pip install canvasxpress[dash]Then create a demo file, such asapp.py, and insert:fromdashimportDash,htmlfromcanvasxpress.canvasimportCanvasXpressfromcanvasxpress.render.dashimportCXElementFactoryg_app=Dash(__name__)# No need to create_element many forms of data into CanvasXpress data objects; for example, use this CSV as-is._g_csv=""", Apples, Oranges, BananasSF      ,      4,       1,       2Montreal,      2,       4,       5"""_g_cx_colors={"background":"#111111","text":"rgb(127,219,255)","bars":["rgb(99,110,250)","rgb(239,85,59)"],}# Work with data as normal Python values.  cx_data could also have been a DataFrame, JSON, URL, etc._g_cx_chart=CanvasXpress(render_to="fruit_consumption",data=_g_csv,config={"colors":_g_cx_colors["bars"],"graphOrientation":"vertical","smpLabelRotate":90,"plotBox":True,"plotBoxColor":"White","background":_g_cx_colors["background"],"theme":"Plotly","xAxis":["Fruit","City"],"xAxisTitle":"Amount","xAxis2Show":False,"xAxisMinorTicks":False,"axisTitleColor":_g_cx_colors["text"],"axisTickColor":_g_cx_colors["text"],"legendColor":_g_cx_colors["text"],"smpTitle":"Fruit","smpTitleFontColor":_g_cx_colors["text"],"smpLabelFontColor":_g_cx_colors["text"],},width=650,height=450,)# Applicationg_app.layout=html.Div(style={"backgroundColor":_g_cx_colors["background"]},children=[html.H1(children="Hello Dash",style={"textAlign":"center","color":_g_cx_colors["text"]},),html.H2(children=("An Example of the Advanced CanvasXpress and CXDashElementFactory"" Classes for Plotting a CanvasXpress Chart"),style={"textAlign":"center","color":_g_cx_colors["text"]},),html.Div(id="chart-container",children=[html.Div(id="cx-container",style={"textAlign":"center"},children=CXElementFactory.render(_g_cx_chart),),],),],)if__name__=="__main__":g_app.run_server(debug=True)Run the App and View the PageOn the command line, execute:python3 app.pyAnd output similar to the following will be provided:Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)Browsing tohttp://127.0.0.1:8050/will result in a page with a CanvasXpress chart, which is being hosted by the Dash
framework:Congratulations!  You have created a Plotly Dash CanvasXpress app!A Quick Flask ExampleFlaskis a popular lean Web development framework for Python based applications.
Flask applications can serve Web pages, RESTful APIs, and similar backend service concepts. This example shows how to
create a basic Flask application that provides a basic Web page with a CanvasXpress chart composed using Python in the
backend.The concepts in this example equally apply to other frameworks that can serve Web pages, such as Django and Tornado.Create a Basic Flask AppA basic Flask app provides a means by which:A local development server can be startedA function can respond to a URLFirst install Flask and CanvasXpress for Python:pip install -U Flask canvasxpressThen create a demo file, such asapp.py, and insert:# save this as app.pyfromflaskimportFlaskapp=Flask(__name__)@app.route('/')defcanvasxpress_example():return"Hello!"On the command line, execute:flask runAnd output similar to the following will be provided:Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)Browsing tohttp://127.0.0.1:5000/will result in a page with the textHello!.Add a ChartCanvasXpress for Python can be used to define a chart with various attributes and then generate the necessary HTML and
Javascript for proper display in the browser.Add atemplatesdirectory to the same location as theapp.pyfile, and inside add a file
calledcanvasxpress_example.html. Inside the file add:<html><head><metacharset="UTF-8"><title>Flask CanvasXpress Example</title><!-- 2. Include the CanvasXpress library --><linkhref='https://www.canvasxpress.org/dist/canvasXpress.css'rel='stylesheet'type='text/css'/><scriptsrc='https://www.canvasxpress.org/dist/canvasXpress.min.js'type='text/javascript'></script><!-- 3. Include script to initialize object --><scripttype="text/javascript">onReady(function(){{{canvas_source|safe}}})</script></head><body><!-- 1. DOM element where the visualization will be displayed -->{{canvas_element|safe}}</body></html>The HTML file, which usesJinja syntaxachieves three things:Provides a location for a<div>element that marks where the chart will be placed.References the CanvasXpress CSS and JS files needed to illustrate and operate the charts.Provides a location for the Javascript that will replace the chart<div>with a working element on page load.Going back to our Flask app, we can add a basic chart definition with some data to our example function:fromflaskimportFlask,render_templatefromcanvasxpress.canvasimportCanvasXpressapp=Flask(__name__)@app.route('/')defcanvasxpress_example():# Define a CX bar chart with some basic datachart:CanvasXpress=CanvasXpress(data={"y":{"vars":["Gene1"],"smps":["Smp1","Smp2","Smp3"],"data":[[10,35,88]]}},config={"graphType":"Bar"})# Get the HTML parts for use in our Web page:html_parts:dict=chart.render_to_html_parts()# Return a Web page based on canvasxpress_example.html and our HTML partsreturnrender_template("canvasxpress_example.html",canvas_element=html_parts["cx_canvas"],canvas_source=html_parts["cx_js"])Run the App and View the PageRerun the flask app on the command line and browse to the indicated IP and URL. A page similar to the following will be
displayed:Congratulations!  You have created a Flask CanvasXpress app!