Matplotlib

matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell, web application servers, and many graphical user interface toolkits.

matplotlib tries to make easy things easy and hard things possible. You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc, with just a few lines of code. For a sampling, see the screenshots, thumbnail gallery, and examples directory


In [ ]:
import numpy as np
%pylab inline

Let's create some graphics using a function that increase in its randomness in "linear space":


In [ ]:
plot(np.linspace(0, 10, 100) * np.random.random(100))

Notice that many "defaults" such as color, line style, markings, etc. have been made for you -- and all of them look pretty good.

Let's try to modify these defaults.


In [ ]:
plot(np.linspace(0, 10, 100) * np.random.random(100), 
     color='red', linewidth=2, linestyle="--")

Let's plot more than 1 line graph at a time where noise variance does NOT increase over the horizontal axis:


In [ ]:
plot(np.linspace(0, 10, 100) + np.random.random(100), 
     color='red', linewidth=2, linestyle="--")
plot(np.linspace(0, 10, 100) - np.random.random(100), 
     color='blue', linewidth=2, linestyle="-")

Let's look at another type of visualization: histogram:


In [ ]:
hist(np.linspace(0, 10, 100) + np.random.random(100) * 3,
     color='green')

matplotlib has a lot of options, particularly with the recent release of matplotlib 2.0.

Bokeh

Bokeh is a Python interactive visualization library that targets modern web browsers for presentation. Its goal is to provide elegant, concise construction of novel graphics in the style of D3.js, and to extend this capability with high-performance interactivity over very large or streaming datasets. Bokeh can help anyone who would like to quickly and easily create interactive plots, dashboards, and data applications.


In [ ]:
import numpy as np
from bokeh.plotting import figure, output_file, show

Plotting data in basic Python lists as a line chart including zoom, pan, resize, save, and other tools is simple and straightforward:


In [ ]:
a = np.arange(10)
b = np.random.randn(10)

Let's create a HTML page with interactive graphics.


In [ ]:
output_file("lines.html")

create a new plot with a title and axis labels


In [ ]:
p = figure(title="Bokeh Line", 
           x_axis_label='x', 
           y_axis_label='y')

add a line renderer with legend and line thickness


In [ ]:
p.line(a, b, legend="Random Walk", line_width=2)

In [ ]:
# let's finally see the results
show(p)

When you execute this script, you will see that a new output file "lines.html" is created, and that a browser automatically opens a new tab to display it.

That's pretty cool with almost no web development!

The basic steps to creating plots with the bokeh.plotting interface are:

  • Prepare some data (in this case plain python lists).
  • Tell Bokeh where to generate output (in this case using output_file(), with the filename "lines.html").
  • Call figure() to create a plot with some overall options like title, tools and axes labels.
  • Add renderers (in this case, Figure.line) for our data, with visual customizations like colors, legends and widths to the plot.
  • Ask Bokeh to show() or save() the results.
  • Steps three and four can be repeated to create more than one plot, as shown in some of the examples below.

The bokeh.plotting interface is also quite handy if we need to customize the output a bit more by adding more data series, glyphs, logarithmic axis, and so on. It’s also possible to easily combine multiple glyphs together on one plot as shown below:


In [ ]:
x = np.arange(10)

In [ ]:
y0 = [i**2 for i in x]
y1 = [10**i for i in x]
y2 = [10**(i**2) for i in x]

Output to a static HTML file


In [ ]:
output_file("loglines.html")

Let's be specific about the "tools" we are enabling in this graphics: pan and zoom, box zoom, reset, and save.


In [ ]:
p = figure(
   tools="pan,box_zoom,reset,save",
   y_axis_type="log", y_range=[0.001, 10**11], title="Bokeh with log axis",
   x_axis_label='sections', y_axis_label='particles'
)

p.line(x, x, legend="y=x")
p.circle(x, x, legend="y=x", fill_color="white", size=8)
p.line(x, y0, legend="y=x^2", line_width=3)
p.line(x, y1, legend="y=10^x", line_color="red")
p.circle(x, y1, legend="y=10^x", fill_color="red", line_color="red", size=6)
p.line(x, y2, legend="y=10^x^2", line_color="orange", line_dash="4 4")

Remember to call show on the figure:


In [ ]:
show(p)

Bokeh Glyphs

Glyphs are the basic visual marks that Bokeh can display. At the lowest level, there are glyph objects, such as Line. If you are using the low-level bokeh.models interface, it is your responsibility to create and coordinate all the various Bokeh objects, including glyph objects and their data sources. To make life easier, the bokeh.plotting interface exposes higher level glyph methods such as the Figure.line method used in the first example. The second example also adds in calls to Figure.circle to display circle and line glyphs together on the same plot. Besides lines and circles, Bokeh makes many additional glyphs and markers available.

The visual appearance of a glyph is tied directly to the data values that are associated with the glyph’s various attributes. In the example above we see that positional attributes like x and y can be set to vectors of data. But glyphs also have some combination of Line Properties, Fill Properties, and Text Properties to control their appearance. All of these attributes can be set with “vectorized” values as well. We will show examples of this below.

Guides and Annotations

Bokeh plots can also have other visual components that aid presentation or help the user make comparisons. These fall into two categories.

  1. Guides are visual aids that help users judge distances, angles, etc. These include grid lines or bands, axes (such as linear, log, or datetime) that may have ticks and tick labels as well.
  2. Annotations are visual aids that label or name parts of the plot. These include titles, legends, etc.

Ranges

Ranges describe the data-space bounds of a plot. By default, plots generated with the bokeh.plotting interface come configured with DataRange1d objects that try to automatically set the plot bounds to encompass all the available data. But it is possible to supply explicit Range1d objects for fixed bounds. As a convenience these can also typically be spelled as 2-tuples or lists:

p = figure(x_range=[0,10], y_range=(10, 20))

Resources

To generate plots, the client library BokehJS JavaScript and CSS code must be loaded into the browser. By default, the output_file() function will load BokehJS from http://cdn.pydata.org . However, you can also configure Bokeh to generate static HTML files with BokehJS resources embedded directly inside, by passing the argument mode="inline" to the output_file() function.

Vectorized colors and sizes

Let's see how to provide sequences of data values for glyph attributes like fill_color and radius.


In [ ]:
# let's create and x and y random array with length 1000
N = 4000
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100

# let's also randomly determine the radii for the bubbles
radii = np.random.random(size=N) * 1.5

# create some random RGB hex codes to create color variation
colors = [
    "#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y)
]

Next: let's define the specific user controls that we want to reify in this graphics:


In [ ]:
TOOLS='resize,pan,wheel_zoom,box_zoom,reset,hover'

Now is time to actually create the graphics:


In [ ]:
p = figure(tools=TOOLS, 
           x_range=(0,100), 
           y_range=(0,100),
           title="Interactive Bubble Chart",
           x_axis_type="linear",
           y_axis_type="linear"
          )

Finally, let's add bubbles as represented by circles to the chart:


In [ ]:
p.circle(x, y, radius=radii, fill_color=colors, 
         fill_alpha=0.5, line_color=None)
output_file('bubbles.html', title="Bokeh Bubble Chart", mode='cdn')
show(p)

Now, that's pretty cool!

For more information on how to use Bokeh to impress your colleagues and bosses, check out resources here: http://bokeh.pydata.org/


In [ ]: