# Plotly Python

I am plotting a funnel in plotly using python, and even though I have adjusted the font size to 18, the numbers at the really bottom for the red part are very small and arent visible. Python python-3.x plotly plotly-python. Asked Mar 26 at 17:57. 121 6 6 bronze badges. Plotly Python Open Source Graphing Library. Plotly's Python graphing library makes interactive, publication-quality graphs. Examples of how to make line plots. Streamtubes in Plotly with Python Before we introduce this seriously cool visualization, we’d like to announce that plotly.py has surpassed 5 million downloads! Thank you for helping us reach this milestone! Once Upon a Time It was the year 2008. If you wanted to create 3-D plots for interactive scientific data visualization, the Mayavi. Try our free courses in Python, R, SQL, and more. Complete hands-on exercises and follow short videos from expert instructors. From Python & R tab, you can view code corresponding to current plot in Python, R, JSON, Matlab etc. Following snapshot shows Python code for the plot as generated above −. Setting for Offline Plotting. Plotly allows you to generate graphs offline and save them in local machine.

• Plotly Tutorial
• Plotly Useful Resources

The following chapter deals with the settings for the online and offline plotting. Let us first study the settings for online plotting.

## Settings for online plotting

Data and graph of online plot are save in your plot.ly account. Online plots are generated by two methods both of which create a unique url for the plot and save it in your Plotly account.

• py.plot() − returns the unique url and optionally open the url.

• py.iplot() − when working in a Jupyter Notebook to display the plot in the notebook.

We shall now display simple plot of angle in radians vs. its sine value. First, obtain ndarray object of angles between 0 and 2π using arange() function from numpy library. This ndarray object serves as values on x axis of the graph. Corresponding sine values of angles in x which has to be displayed on y axis are obtained by following statements −

Next, create a scatter trace using Scatter() function in graph_objs module.

Use above list object as argument to plot() function.

Save following script as plotly1.py

Execute the above mentioned script from command line. Resultant plot will be displayed in the browser at specified URL as stated below.

Just above the displayed graph, you will find tabs Plot, Data, Python & Rand Forking history.

Currently, Plot tab is selected. The Data tab shows a grid containing x and y data points. From Python & R tab, you can view code corresponding to current plot in Python, R, JSON, Matlab etc. Following snapshot shows Python code for the plot as generated above −

## Setting for Offline Plotting

Plotly allows you to generate graphs offline and save them in local machine. The plotly.offline.plot() function creates a standalone HTML that is saved locally and opened inside your web browser.

Use plotly.offline.iplot() when working offline in a Jupyter Notebook to display the plot in the notebook.

Note − Plotly's version 1.9.4+ is needed for offline plotting.

Change plot() function statement in the script and run. A HTML file named temp-plot.html will be created locally and opened in web browser.

## Introduction

I’ve written quite a bit about visualization in python - partially because the landscapeis always evolving. Plotly stands out as one of the tools that has undergone a significantamount of change since my first post in 2015. If you have not looked at using Plotly for pythondata visualization lately, you might want to take it for a spin. This article will discusssome of the most recent changes with Plotly, what the benefits are and why Plotly is worthconsidering for your data visualization needs.

## Previous Observations

In 2015, I compared several of the python visualization libraries, including Plotly.At that time, I had two main concerns with Plotly:

1. The library required you to setup an account and get an API key. You did not haveto post your visualizations to the Plotly servers but the extra steps for the API keywere a bit of an extra hurdle.
2. The API was not very streamlined. It was a bit clunky and didn’t “click” withme right away.

Both of these barriers have been resolved with updates in the last year.

In March 2019, Plotly released Plotly Express. This new high-level library addressedmany of the concerns I had about the pythonic nature of the Plotly API which I will discusslater in this article.

The one minor issue with Plotly Express at the initial release was that it was a a separate packagefrom Plotly so it was an extra installation step.

Fast forward to July 2019 and Plotly 4.0 was released. This release marked two bigmilestones that motivated me to spend some more time with Plotly. The biggest change wasthat Plotly 4.0 and above would be “offline only” by default. In other words, no needfor an API key. You can still use the online mode if you want to but there is acompletely separate package for that.

The other big benefit of the 4.0 series is that Plotly Express was integrated back intothe base Plotly package. There is no need to install an additional Plotly Express package.You can `conda install` or `pip install` Plotly and get the Plotly Express APIfor free.

As of this article, Plotly has continued to be improve and receive updates. I have beenusing it quite a bit since the 4.6 release and feel like it has reached the point where itis a a good choice for quickly building and customizing interactive visualizations.

## Benefits of Plotly Express

In a recent guest post Duarte O.Carmo mentioned some of the benefits of Plotly. Iecho his comments and want to expand on them with my own observations after using it for a few months.

### Consistent API

When I create visualizations, I iterate through many different approaches beforeI find one that really works. It is important to me that I can easily switch visualizationapproaches with minimal code changes. The “API fit” likely varies by person but my experienceis that Plotly Express fits my thought process. The Plotly Express approach is somewhat similarto seaborn. The function signature is pretty simple and powerful.

To demonstrate, we will use some cereal data that I cleaned up for clarity:

The data contains some simple characteristics of various cereals:

If we want to look at the relationships between the `rating` and `sugars` andinclude the cereal name as a hover label:

Using this approach, it is easy to switch chart types by changing the function call.For example, it is pretty clear what each of these chart types will do:

• `px.scatter()`
• `px.line()`
• `px.bar()`
• `px.histogram()`
• `px.box()`
• `px.violin()`
• `px.strip()`

For my work, these chart types cover 80-90% of what I do on a day to day basis.

Here is another example. This time it’s a static histogram image:

In addition to the different chart types, most types support the same basic function signatureso you can easily facet the data or change colors or sizes based on the values in your DataFrame:

Even if you have never used Plotly before, you should have a basic idea of what each ofthese options does and understand how useful it can be to display your data in many differentways by making minor changes to the function calls. The interactivity also makes it very easyto explorer and get a better understanding of the underlying data.

### Many chart types

In addition to the basic chart types described above, Plotly has several advanced/specializedcharts such as the funnel_chart, timeline, treemap, sunburst and geographic maps.

I think basic chart types should be the starting point for analysis but sometimes a more complex visualizationcan be really effective. It’s worth your time to check out all the options here. You neverknow when you might need a more specialized chart type.

For example, a treemap can be useful for understanding the hierarchical nature of your data.This chart type is not commonly available in other python visualization libraries whichis another nice positive for Plotly:

You can switch the concepts around and use a sunburst (don’t call me a pie) chart:

### Saving images

Suprisingly one of the challenges with many plotting libraries is that it is not easyto save static `.png`, `.jpeg` or `.svg` files. This is one area where matplotlib really shinesand many of the javascript plotting tools struggle - especially where corporatesystems are locked down & firewall settings cause problems. I have certainly done my shareof taking screen shots and pasting images into a PowerPoint or email.

### Plotly Python Example

Plotly recently released kaleido which makes it much easier to save static images in multipleformats. The announcement goes into much more detail about the challenges of developinga stable, fast solution for exporting images. I have personally struggled with some of thesesame challenges. In my usage over the past couple of weeks, kaleido reliably saves highquality images as advertised. For example, saving as `.svg` makes for much higher qualityimages in my presentations.

In the examples in this article, I’ve used a mix of static `.png` and dynamic HTML images.

For instance, if I want to save a small version (`scale=.85`) of the sunburst chart:

I have been able to use this approach in a native Windows environment as well as with WSLand suspect it will work on MacOS as well. I am really glad to see this solution in placefor Plotly and find it suprisingly useful for sharing results.

Plotly also supports saving as standalone HTML. For the treemap, I wanted to include the raw HTMLin this static blog so I used this method to write a snippet that will serve the javascriptfiles from a cdn and contain all the markup within a `<div>` tag.

I included the generated html my static blog post and Plotly takes care of the interactivecomponents. Pretty nice!

### Python Matplotlib

When I work with data, I always end up with a pandas DataFrame and most of the time it’s intidy format. Plotly natively understands the pandas DataFrame so you do not need additionaltransformation of the data prior to plotting.

Plotly can be even more integrated with pandas. Pandas 0.25 and above have an option todefine different plotting back ends and Plotly can be enabled in such a fashion:

Which allows you to create a visualization using a combination of the pandas and Plotly API.Here is an example histogram using this combination:

One other recent change to plotly Express is that it supports “wide-form” as well astidy (aka long-form) data. This feature allows you to pass multiple DataFrame columnsinstead of trying to `melt` the data into the right format. Refer to the documentationfor more examples.

### Figure customization

Plotly Express supports quick and straightforward modifications of visualizations. However,there are times when you need to make fine-tuned customizations. This quote from the PlotlyExpress intro article sums up the approach nicely:

Plotly Express is to Plotly.py what Seaborn is to matplotlib: a high-level wrapper thatallows you to quickly create figures, and then use the power of the underlying API andecosystem to make modifications afterwards.

You can customize the final Plotly Express chart using `update_layout`, `add_shape`,`add_annotation``add_trace` or defining a `template`. The documentationcontains many detailed examples.

Here is an example of customizing several components of the `sodium` and `potass`distribution:

The syntax is relatively straightforward but it can take some time to work through the documentationto find the right syntax combination. This is one area where the relative youth of this packagemeans there are not as many customization examples. I am sure this situation will improve as we getmore examples in the wild.

## Interactive options

By default, all of the Plotly visualizations are interactive (as demonstrated in this article).There are still times when you need to make more robust applications.

Plotly includes it’s own library called Dash that provides a lot of features and functionalityfor building your own custom apps. I wrote about an example in this post.

The new kid on the data apps space is Streamlit and it includes support fordisplaying Plotly charts using `st.plotly_chart()`

Here is a complete streamlit app that allows you to select which value you want to compareto the `rating`:

You can run the file using:

This is a simple example but shows how simple it is to create an interactive applicationwith streamlit and Plotly.

## Summary

Python’s visualization landscape continues to evolve which is good but can be difficult tokeep up with. Plotly’s more recent updates, including Plotly Express and the kaleido libraryfor image export make Plotly a good option to consider for quickly making customized,attractive and interactive data visualizations. The ability to generate high quality staticimages or interactive HTML versions using streamlit or Dash is a very nice bonus as well.