Visualization In Python With Matplotlib

3y ago
44 Views
4 Downloads
154.19 KB
29 Pages
Last View : 6d ago
Last Download : 3m ago
Upload by : Arnav Humphrey
Transcription

Visualization in Python with matplotlibPete AlonziResearch Data Services UVa LibraryMarch 1, 2016

Check us outdata.library.virginia.edu

What we’re gonna do today 2-3:30Get everyone up and running with pythonpython interfacesLoading matplotlibPlotting 101 (create and save)Histograms, scatter plotsCosmeticsmultiplots

Installation of Python Two Notes– Language (python) vs language distribution (anaconda)– Python 2 vs Python 3 https://www.continuum.io/downloads1. Scroll to your operating system2. Click on the blue box under Python 2.73. Follow the instructions

Interfaces Command line interpreter (and ipython)Commandline script executionIpython notebook / jupyterSpyder (generalize to ide)

Loading matplotlib It depends on your interface

A basic plot C:\Users\lpa2a python import matplotlib.pyplot as pltx range(10)plt.plot(x)plt.show()Why blue?Why a line?Why a line with slope of 1?Why does it hang after show?

Saving a plot There are two ways to save the plot:– Use the command line: plt.savefig(‘test.pdf’) Must be done before the show command– Use the gui: Click the save icon Type in the file name select the file type

Window control Notice when we use plt.show() we losecontrol. To regain control we must close the plotwindow. Now we’ll go through other ways ofinteracting with matplotlib to avoid thisproblem.

IPython %pylab Instead of loading up python at the command line withpython use ipython instead. Ipython has a special plotting mode which you load byissuing the command %pylab C:\Users\lpa2a ipython In [1]: %pylab Now we can try our basic plot again.––––Don’t need to load matplotliabWe don’t need to use the “plt.”We don’t loose control when we plotPlot appears on plot command, no more show()

Command line scrip execution Let’s take a look at C:\Users\lpa2a\plot.py

Ipython Notebook Launch from start menu Click “New Notebook”– In []: %pylab– Or– In []: %pylab inline

Spyder Runs the ipython interpreter– Use %pylab or import– Nb: cannot use “Run File” with %pylab

A quick note on appearance In the active plot window we observe a grayborder In the saved plot we observe a white border

Plot Generators There are a few functions in matplotlib thatwill cause a plot to be generated. So far we have worked with plot( ). Now we’ll look at a couple more– hist( )– scatter( )

Histograms

Histogram To plot a histogram we don’t use the function plot. Weuse the function hist––––import numpy as npimport matplotlib.pyplot as pltplt.hist(np.random.randn(1000))plt.show() All of the tricks we just learned to manipulate the plotstill work Here’s some examples for the binning– plt.hist(np.random.randn(1000),bins 25)– plt.hist(np.random.randn(1000),bins [5,-4,-3,-2,-1,0,1,2,3,4,5])17

Scatter Plot Use the function scatter()– 1000))– If using pylab– scatter(randn(1000),randn(1000))18

plot( ) So far we have used a simple implementationof plot. Let’s look deeper. %pylabplot(range(10)) #generatesclf()x arange(0,2*pi,0.2)plot(x,sin(x))x values

Multiplots To add multiple plots repeat the plot call– %pylab– x arange(0,2*pi,0.2)– plot1 plot(x,sin(x))– plot2 plot(x,cos(x)) Now to add a legend– plot1 plot(x,sin(x),label ‘sin’)– plot2 plot(x,cos(x),label ‘cos’)– legend(loc ‘best’)20

Subplots Multiple plots in the same figurePlotfigure21

Subplots For better control we will explicitly catch ourobjects––––––%pylabfig figure()sub1 fig.add subplot(2,2,1)sub2 fig.add subplot(2,2,3)plt.plot(arange(10))Use subplot(221) to switch active plot (demo) There is a function to do it all at once– fig,subs plt.subplots(3,3)Nb: need plt.show() on this one22

Let’s make our plot presentable C:\users\lpa2a ipython --pylab In[1]: plot(cos(arange(0,2*pi,0.2))) Grey backgroundAxis labels too smallPlot touches axisPlot not centered on axisHorizontal axis values aren’t what we wantNo axis labelsLine thicknessLine style23

Ranges and Values Set axis range– axis([-5,37,-1.5,1.5]) Change horizontal axis values– x arange(0,2*pi,0.2)– y cos(x)– plot(x,y)24

Labels and LaTeX Set axis labels– xlabel(‘x’,fontsize 20)– ylabel(‘cos(x)’)– title(‘Cosine’) You can use LaTeX as well– title(r’ \cos(x) ’) http://matplotlib.org/users/pyplot tutorial.html25

Linestyles You have a lot of freedom in choosing a linestyle. They can be expressed explicitly– plot(x,linestyle ‘--’) The same goes for line color– plot(x,color ‘g’) But you can also use shorthand– plot(x,’g--’)26

Linestyles II matplotlib automatically interpolates betweenthe points and puts in a line. To emphasize thepoints you can add markers.– plot(range(10),’o’) # markers, no line– plot(range(10),’o-’) # markers, line– plot(range(10),marker ‘o’) Set line thickness– pl plot(arange(10))– setp(pl,linewidth 5)27

One Page to Rule them All http://matplotlib.org/api/pyplot api.html– Comprehensive– Navigate with searching– Eg: ctrl f “.plot(“

Questions

Visualization in Python with matplotlib Pete Alonzi Research Data Services UVa Library March 1, 2016. Check us out data.library.virginia.edu. What we’re gonnado today 2-3:30 Get everyone up and running with python python interfaces Loading matplotlib Plotting 101 (create and save)

Related Documents:

o integrates code (e.g. python), code output (e.g. plots) and documentation pandas: o python library for data processing o fast, powerful, flexible, easy to use o integrates matplotlib matplotlib: o python library for data visualization o enables DV in matlab style o is platform independent and very robust

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

Figure 2. Matplotlib Consistently Dominates Data Visualization Space . In the chart above, you can clearly see that matplotlib dominates the open source data visualization space. Matplotlib is consistently more popular than Seaborn, Plotly, and ggplot based on the aggregated number of new iles committed per day that mention

Visit : python.mykvs.in for regular updates Data Handling using Pandas -1 Visit : python.mykvs.in for regular updates Python Library –Matplotlib Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.It is used to create 1. Develop publication quality plots with just a few lines of code 2.

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

Basic Description Logics Franz Baader Werner Nutt Abstract This chapter provides an introduction to Description Logics as a formal language for representing knowledge and reasoning about it. It first gives a short overview of the ideas underlying Description Logics. Then it introduces syntax and semantics, covering the basic constructors that are used in systems or have been introduced in the .