Matplotlib

By pjain      Published Dec. 29, 2019, 7:22 a.m. in blog AI-Analytics-Data   

Matplotlib ---> PKJ Quik experience

Setup, QUIK Fixup error 1/17/18

  • virtualenv create/activate ~ /Develop/py3data # for datasci,plotting etc pip install lifelines # uses matplotlib

  • Problem framework not set - fix on macosx by creating a ~ /.matplotlib/matplotlibrc with following text backend: TkAgg

  • Install MacOSX Problems https://docs.python.org/3/using/mac.html http://stackoverflow.com/questions/21842750/installing-python-3-3-on-mac

older PKJ QUIK matplotlib

  • 5/6/2016 CONTINUE Matplot .. @ https://pythonprogramming.net/basic-customization-matplotlib-tutorial/?completed=/converting-date-stamps-matplotlib-tutorial/

  • TODO: Plt with matplot, annotations

Quick Install

* $ pip install matplotlib

* On mac either properly install Py&Matlib framework with XWindows ..
* Or in ~ /.matplotlib/matplotlibrc do 
    backend: TkAgg

* Some users may not want to change the backend for all of their scripts. This page -- http://matplotlib.org/faq/usage_faq.html#what-is-a-backend -- tells another way You have to do this before importing a subpackage of matplotlib or a third-party package that depends on matplotlib.
    import matplotlib
    matplotlib.use('TkAgg')

$ conda install matplotlib
  • Switching to OSX 10.10 (Yosemite). I fixed it by switching to the WXAgg backend. SEE: http://matplotlib.org/1.3.0/faq/usage_faq.html#what-is-a-backend

    fink install wxpython300-py27
    mkdir ~/.matplotlib
    echo "backend : WXAgg" >>~/.matplotlib/matplotlibrc
    
    • If the matplotlibrc file is not found there, put matplotlibrc and check the location with:

      import matplotlib as mpl mpl.get_configdir()

Ex0-0

  • ~ /PythonZ/dataVizMathPlotlib/matplotex1.py

    import matplotlib.pyplot as plt plt.plot([1,2,3],[5,7,4]) plt.show()

Charting

  • Simple line x = [1,2,3,4,5,6,7,8] y = [5,2,4,2,1,4,5,2] plt.plot(x,y, label='Loaded from file!') plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show()

  • Ex3 - bar charts and histograms plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one") plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g') plt.legend() plt.xlabel('bar number') plt.ylabel('bar height') plt.title('Epic Graph\nAnother Line! Whoa') plt.show()

  • Ex3b (freq-analysis) histograms population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48] bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130] plt.hist(population_ages, bins, histtype='bar', rwidth=0.8) plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show()

  • Scatter

    x = [1,2,3,4,5,6,7,8] y = [5,2,4,2,1,4,5,2]

    plt.scatter(x,y, label='skitscat', color='k', s=25, marker="o")

    plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show()

  • Stack Plots with COLORS & LABELS LEGEND

    days = [1,2,3,4,5] # xaxis sleeping = [7,8,6,11,7] # y stack plots eating = [2,3,4,3,2] working = [7,8,7,2,2] playing = [8,5,7,8,13]

    plt.plot([],[],color='m', label='Sleeping', linewidth=5) plt.plot([],[],color='c', label='Eating', linewidth=5) plt.plot([],[],color='r', label='Working', linewidth=5) plt.plot([],[],color='k', label='Playing', linewidth=5)

    plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k'])

    plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show()

  • Pie Chart slices = [7,2,2,13] activities = ['sleeping','eating','working','playing'] cols = ['c','m','r','b'] plt.pie(slices, labels=activities, colors=cols, startangle=90, shadow= True, explode=(0,0.1,0,0), autopct='%1.1f%%') plt.title('Interesting Graph\nCheck it out') plt.show()

Data from CSV

  • Load x,y Simple csv to array import matplotlib.pyplot as plt import csv x = [] y = [] with open('example.csv','r') as csvfile: plots = csv.reader(csvfile, delimiter=',') for row in plots: x.append(int(row[0])) y.append(int(row[1]))

  • Load x,y From numpy import matplotlib.pyplot as plt import numpy as np x, y = np.loadtxt('example.csv', delimiter=',', unpack=True) plt.plot(x,y, label='Loaded from file!')

  • Load from internet - using urllib

Customize Looks

Std matplot

  • Legend

    EX2: With labels and legends

    x = [1,2,3] y = [5,7,4] x2 = [1,2,3] y2 = [10,14,12] plt.plot(x,y,label="First") plt.plot(x2,y2,label="second") plt.xlabel('Plot Numbers') plt.ylabel('y') plt.title('Check it out\nLine2') plt.legend() plt.show()

  • Marker options http://matplotlib.org/api/markers_api.html

ggplot, Seaborn

  • Styles - upgrade look - more sophisticated

    import matplotlib.pyplot as plt plt.style.use('ggplot') x, y = np.loadtxt('example.csv', delimiter=',', unpack=True) plt.plot(x,y, label='Loaded from file!') plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show()

  • ex: mpnumpyline.py import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd plt.style.use('ggplot')

    sns uses df preferentially

    df = pd.read_csv('example.csv') sns.jointplot(data=df, x='x', y='y') sns.plt.show()

  • IRIS dataset of petal species clustering .. iris = sns.load_dataset("iris") sns.pairplot(iris) sns.plt.show()

Matplotlib in Browser

  • Packages
  • http://mpld3.github.io/ - brings together Matplotlib, the popular Python-based graphing library, and D3js, the popular JavaScript library for creating interactive data visualizations for the web. The result is a simple API for exporting your matplotlib graphics to HTML code which can be used within the browser, within standard web pages, blogs, or tools such as the IPython notebook.

  • webplotlib is a Python package to create server-side charts, using Matplotlib. It is readily integrated into a Django project, or used on its own. https://github.com/limist/webplotlib

Matplotlib Overview

r Official 101

r * matplotlib

CU EBK Matplotlib for Python developers Aldrin Yim; Claire Chung; Allen Yu Pub. Date: April 24, 2018

CU EBK Matplotlib 2.0 By Example + Code !downloaded to Parasmac

  • Official

TUTES Py Plotting - Matplotlib

Python Crash Course > Part II: Projects > Installing matplotlib : Safari Books Online

http://opensourceforu.com/2017/02/2d-plotting-using-matplotlib-library/ http://proquest.safaribooksonline.com.rpa.sccl.org/book/programming/python/9781457197185/part-ii-projects/part02_pro02_html#X2ludGVybmFsX0h0bWxWaWV3P3htbGlkPTk3ODE0NTcxOTcxODUlMkZjaDE1bGV2MXNlYzAxX2h0bWwmcXVlcnk9KChGbGFzaykp http://proquest.safaribooksonline.com.rpa.sccl.org/book/programming/javascript/9781491920565/10dot-visualizing-data-with-matplotlib/chapter_matplotlib_html

About

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 (ala MATLAB®* or Mathematica®†), web application servers, and six graphical user interface toolkits.

  • Intro

  • There are two ways Python can be built and installed on Mac OS X. One is as a traditional flat Unix-y shared library. The other is known as a framework install, a file layout similar to other frameworks on OS X where all of the component directories (include, lib, bin) for the product are installed as subdirectories under the main framework directory. The Fink project installs Pythons using the Unix shared library method. Most other distributors, including the Apple-supplied Pythons in OS X, the python.org installers, and the MacPorts project, install framework versions of Python. One of the advantages of a framework installation is that it will work properly with various OS X API calls that require a window manager connection (generally GUI-related interfaces) because the Python interpreter is packaged as an app bundle within the framework.

If you do need the functions in matplotlib that require the GUI functions, the simplest approach may be to switch to MacPorts which also packages matplotlib (port py27-matplotlib) and its dependencies. If so, be careful not to mix packages between Fink and MacPorts. It's best to stick with one or the other unless you are really careful. Adjust your shell path accordingly; it would be safest to remove all of the Fink packages and install MacPorts versions.

Features Overview

  • MatPlot Window
  • home, Fwd/Back "browser nav for chart"
  • Pan, zoom within
  • Configure subplots - eg set axes subset
  • Save eg as .png

Install

Works with Py2.7, ith PY3.6 gets error - RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.

Lib eBooks

Error handling

Django matplotlib !PRIO

r DJ Matplotlib

Django Plotting app - The HowTo describes how to embed matplotlib plots into the admin interface and create a PDF view Matplotlib and Django https://stackoverflow.com/questions/11163485/serving-generated-charts-via-ajax

Tutes

Plot Registered Django Users with Matplotlib Django users Is it possible to output a graph from Matplotlib into Django like this? https://www.pythonanywhere.com/forums/topic/11201/

http://scipy-cookbook.readthedocs.io/items/Matplotlib_Django.html https://www.eriksmistad.no/making-charts-and-outputing-them-as-images-to-the-browser-in-django/ https://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/Django.html https://matplotlib.org/faq/howto_faq.html https://www.packtpub.com/mapt/book/All%20Books/9781847197900/8/ch08lvl1sec04/matplotlib-and-django https://snakeycode.wordpress.com/2014/04/18/dynamically-creating-plots-for-django-using-matplotlib/ https://bitsofpy.blogspot.com/2009/07/matplotlib-in-django.html

SO

https://stackoverflow.com/questions/30531990/matplotlib-into-a-django-template https://stackoverflow.com/questions/1874642/how-to-use-matplotlib-in-django Problems with Django & matplotlib


0 comments

There are no comments yet

Add new comment

Similar posts

Politics and Social Networks

Markov Models Quickstart

Monte Carlo Models, Chains and Monte Carlo Simulation

Datascience, Big Data, Analytics and Visualization Learning Guide