Mostrando entradas con la etiqueta PIP. Mostrar todas las entradas
Mostrando entradas con la etiqueta PIP. Mostrar todas las entradas

jueves, 20 de diciembre de 2018

PIP in python and How to install matplotlib on Windows PC part II 3D IMAGES

PIP in python and How to install matplotlib on Windows PC part II



Add the pyhton.exe to the path environment

C:\Python27>python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>






C:\Python27>python -m pip install -U pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/c2/d7/90f34cb0d83a6c5631cf71dfe64cc1054598c843a92b400e55675cc2ac37/pip-18.1-py2.py3-none-any.whl (1.3MB)
    100% |################################| 1.3MB 595kB/s
Installing collected packages: pip
  Found existing installation: pip 9.0.1
    Uninstalling pip-9.0.1:
      Successfully uninstalled pip-9.0.1
Successfully installed pip-18.1

C:\Python27>

INSTALL PANDAS

C:\>python -m pip install -U pandas
Collecting pandas
  Downloading https://files.pythonhosted.org/packages/f4/19/04e8f29157136e85c977517e71cea1187b971efc80d772c0d8c3967018da/pandas-0.23.4-cp27-cp27m-win32.whl (6.5MB)
    100% |################################| 6.5MB 324kB/s
Requirement already satisfied, skipping upgrade: python-dateutil>=2.5.0 in c:\python27\lib\site-packages (from pandas) (2.7.5)
Requirement already satisfied, skipping upgrade: numpy>=1.9.0 in c:\python27\lib\site-packages (from pandas) (1.15.4)
Requirement already satisfied, skipping upgrade: pytz>=2011k in c:\python27\lib\site-packages (from pandas) (2018.7)
Requirement already satisfied, skipping upgrade: six>=1.5 in c:\python27\lib\site-packages (from python-dateutil>=2.5.0->pandas) (1.12.0)
Installing collected packages: pandas
Successfully installed pandas-0.23.4


Install scikit-learn

C:\>python -m pip install -U scikit-learn
Collecting scikit-learn
  Downloading https://files.pythonhosted.org/packages/4b/4c/08fe2ff9364e0ec793a3c93ebe9471bf6e37c53c0fc64e9ce22a2540d1d1/scikit_learn-0.20.2-cp27-cp27m-win32.whl (4.5MB)
    100% |################################| 4.5MB 3.2MB/s
Requirement already satisfied, skipping upgrade: scipy>=0.13.3 in c:\python27\lib\site-packages (from scikit-learn) (1.2.0)
Requirement already satisfied, skipping upgrade: numpy>=1.8.2 in c:\python27\lib\site-packages (from scikit-learn) (1.15.4)
Installing collected packages: scikit-learn
Successfully installed scikit-learn-0.20.2


install numpy

C:\Users\robertoperez>python -m pip install -U numpy
Collecting numpy
  Downloading https://files.pythonhosted.org/packages/a7/01/8f627ce395d4e537dd25865c71302b70e4537d71176f7207c038d0292998/numpy-1.15.4-cp27-none-win32.whl (9.9MB)
    100% |################################| 9.9MB 90kB/s
Installing collected packages: numpy
Successfully installed numpy-1.15.4

C:\Users\robertoperez>


install scipy

C:\Python27\python.exe: No module named scipy

C:\Users\robertoperez>python -m pip install -U scipy
Collecting scipy
  Downloading https://files.pythonhosted.org/packages/8d/3e/8b832f5df4d06190c280585278886ecda99ff10d25be0a685f78f79009a0/scipy-1.2.0-cp27-cp27m-win32.whl (27.3MB)
    100% |################################| 27.3MB 96kB/s
Collecting numpy>=1.8.2 (from scipy)
  Downloading https://files.pythonhosted.org/packages/a7/01/8f627ce395d4e537dd25865c71302b70e4537d71176f7207c038d0292998/numpy-1.15.4-cp27-none-win32.whl (9.9MB)
    100% |################################| 9.9MB 159kB/s
Installing collected packages: numpy, scipy
  Found existing installation: numpy 1.15.4
    Uninstalling numpy-1.15.4:
      Successfully uninstalled numpy-1.15.4
Successfully installed numpy-1.15.4 scipy-1.2.0


AGREGAMOS LAS LIBRERIAS IMPORTANTES A 1-2021

import pandas_datareader as pdr
import datetime
import pandas as pd

import matplotlib.pyplot as plt

C:\Users\roberto.martinez>python -m pip install pandas_datareader
Collecting pandas_datareader
  Downloading pandas_datareader-0.9.0-py3-none-any.whl (107 kB)
     |████████████████████████████████| 107 kB 1.7 MB/s
Requirement already satisfied: pandas>=0.23 in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from pandas_datareader) (1.2.0)
Requirement already satisfied: numpy>=1.16.5 in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from pandas>=0.23->pandas_datareader) (1.19.5)
Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from pandas>=0.23->pandas_datareader) (2.8.1)
Requirement already satisfied: pytz>=2017.3 in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from pandas>=0.23->pandas_datareader) (2020.5)
Requirement already satisfied: six>=1.5 in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from python-dateutil>=2.7.3->pandas>=0.23->pandas_datareader) (1.15.0)
Collecting requests>=2.19.0
  Downloading requests-2.25.1-py2.py3-none-any.whl (61 kB)
     |████████████████████████████████| 61 kB 3.8 MB/s
Collecting certifi>=2017.4.17
  Downloading certifi-2020.12.5-py2.py3-none-any.whl (147 kB)
     |████████████████████████████████| 147 kB 3.2 MB/s
Collecting chardet<5,>=3.0.2
  Downloading chardet-4.0.0-py2.py3-none-any.whl (178 kB)
     |████████████████████████████████| 178 kB 3.3 MB/s
Collecting idna<3,>=2.5
  Downloading idna-2.10-py2.py3-none-any.whl (58 kB)
     |████████████████████████████████| 58 kB 4.1 MB/s
Collecting urllib3<1.27,>=1.21.1
  Downloading urllib3-1.26.2-py2.py3-none-any.whl (136 kB)
     |████████████████████████████████| 136 kB 6.8 MB/s
Collecting lxml
  Downloading lxml-4.6.2-cp39-cp39-win_amd64.whl (3.5 MB)
     |████████████████████████████████| 3.5 MB 6.8 MB/s
Installing collected packages: urllib3, idna, chardet, certifi, requests, lxml, pandas-datareader
  WARNING: The script chardetect.exe is installed in 'C:\Users\roberto.martinez\AppData\Local\Programs\Python\Python39\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed certifi-2020.12.5 chardet-4.0.0 idna-2.10 lxml-4.6.2 pandas-datareader-0.9.0 requests-2.25.1 urllib3-1.26.2


+++++++++++++++

C:\Users\roberto.martinez>python -m pip install datetime
Collecting datetime
  Downloading DateTime-4.3-py2.py3-none-any.whl (60 kB)
     |████████████████████████████████| 60 kB 1.2 MB/s
Requirement already satisfied: pytz in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from datetime) (2020.5)
Collecting zope.interface
  Downloading zope.interface-5.2.0-cp39-cp39-win_amd64.whl (196 kB)
     |████████████████████████████████| 196 kB 2.2 MB/s
Requirement already satisfied: setuptools in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from zope.interface->datetime) (49.2.1)
Installing collected packages: zope.interface, datetime
Successfully installed datetime-4.3 zope.interface-5.2.0

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

C:\Users\roberto.martinez>python -m pip install matplotlib
Collecting matplotlib
  Downloading matplotlib-3.3.3-cp39-cp39-win_amd64.whl (8.5 MB)
     |████████████████████████████████| 8.5 MB 3.3 MB/s
Requirement already satisfied: numpy>=1.15 in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from matplotlib) (1.19.5)
Requirement already satisfied: python-dateutil>=2.1 in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from matplotlib) (2.8.1)
Collecting cycler>=0.10
  Downloading cycler-0.10.0-py2.py3-none-any.whl (6.5 kB)
Requirement already satisfied: six in c:\users\roberto.martinez\appdata\local\programs\python\python39\lib\site-packages (from cycler>=0.10->matplotlib) (1.15.0)
Collecting kiwisolver>=1.0.1
  Downloading kiwisolver-1.3.1-cp39-cp39-win_amd64.whl (51 kB)
     |████████████████████████████████| 51 kB 3.8 MB/s
Collecting pillow>=6.2.0
  Downloading Pillow-8.1.0-cp39-cp39-win_amd64.whl (2.2 MB)
     |████████████████████████████████| 2.2 MB 6.4 MB/s
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3
  Downloading pyparsing-2.4.7-py2.py3-none-any.whl (67 kB)
     |████████████████████████████████| 67 kB 2.3 MB/s
Installing collected packages: pyparsing, pillow, kiwisolver, cycler, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.3.1 matplotlib-3.3.3 pillow-8.1.0 pyparsing-2.4.7


C:\Users\robertoperez>python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pylab
>>> x = [i/10 for i in range(0, 100)]
>>> y = [i*i for i in x]
>>> pylab.plot(x, y)
[<matplotlib.lines.Line2D object at 0x082F0190>]
>>> pylab.show()


Installing scikit-learn

Note
 
If you wish to contribute to the project, it’s recommended you install the latest development version.

Installing the latest release

Scikit-learn requires:
  • Python (>= 2.7 or >= 3.4),
  • NumPy (>= 1.8.2),
  • SciPy (>= 0.13.3).
Warning
 
Scikit-learn 0.20 is the last version to support Python 2.7 and Python 3.4. Scikit-learn 0.21 will require Python 3.5 or newer.
If you already have a working installation of numpy and scipy, the easiest way to install scikit-learn is using pip
pip install -U scikit-learn
or conda:
conda install scikit-learn
If you have not installed NumPy or SciPy yet, you can also install these using conda or pip. When using pip, please ensure that binary wheels are used, and NumPy and SciPy are not recompiled from source, which can happen when using particular configurations of operating system and hardware (such as Linux on a Raspberry Pi). Building numpy and scipy from source can be complex (especially on Windows) and requires careful configuration to ensure that they link against an optimized implementation of linear algebra routines. Instead, use a third-party distribution as described below.
If you must install scikit-learn and its dependencies with pip, you can install it as scikit-learn[alldeps]. The most common use case for this is in a requirements.txt file used as part of an automated build process for a PaaS application or a Docker image. This option is not intended for manual installation from the command line.
Note
 
For installing on PyPy, PyPy3-v5.10+, Numpy 1.14.0+, and scipy 1.1.0+ are required.
For installation instructions for more distributions see other distributions. For compiling the development version from source, or building the package if no distribution is available for your architecture, see the Advanced installation instructions.

Third-party Distributions

If you don’t already have a python installation with numpy and scipy, we recommend to install either via your package manager or via a python bundle. These come with numpy, scipy, scikit-learn, matplotlib and many other helpful scientific and data processing libraries.








let's play plooting a parabola

Let's plot, ploting examples ,a parabol, in python
>>> import pylab
>>> x = [i for i in range(-100, 100)]
>>> y = [i*i for i in x]
>>> pylab.plot(x, y)
[<matplotlib.lines.Line2D object at 0x071FAE50>]
>>> pylab.show()



The equation of a simplest parabola is x= y^2





>>> import pylab
>>> x = [i for i in range(-100, 100)]
>>> y = [i*i for i in x]
>>> z = [i*i for i in x]
>>> pylab.plot(x, y,z)
[<matplotlib.lines.Line2D object at 0x071FAF50>, <matplotlib.lines.Line2D object at 0x0763D110>]
>>> pylab.show()


Surface plots

Axes3D.plot_surface(XYZ*args**kwargs)
Create a surface plot.
By default it will be colored in shades of a solid color, but it also supports color mapping by supplying the cmap argument.
The rstride and cstride kwargs set the stride used to sample the input data to generate the graph. If 1k by 1k arrays are passed in, the default values for the strides will result in a 100x100 grid being plotted. Defaults to 10. Raises a ValueError if both stride and count kwargs (see next section) are provided.
The rcount and ccount kwargs supersedes rstride and cstride for default sampling method for surface plotting. These arguments will determine at most how many evenly spaced samples will be taken from the input data to generate the graph. This is the default sampling method unless using the ‘classic’ style. Will raise ValueError if both stride and count are specified. Added in v2.0.0.
ArgumentDescription
XYZData values as 2D arrays
rstrideArray row stride (step size)
cstrideArray column stride (step size)
rcountUse at most this many rows, defaults to 50
ccountUse at most this many columns, defaults to 50
colorColor of the surface patches
cmapA colormap for the surface patches.
facecolorsFace colors for the individual patches
normAn instance of Normalize to map values to colors
vminMinimum value to map
vmaxMaximum value to map
shadeWhether to shade the facecolors
Other arguments are passed on to Poly3DCollection


shapes in #D

>>> from mpl_toolkits.mplot3d import Axes3D
>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> from matplotlib.ticker import LinearLocator, FormatStrFormatter
>>> import numpy as np
>>> fig = plt.figure()
>>> ax = fig.gca(projection='3d')
>>> X = np.arange(-5, 5, 0.25)
>>> Y = np.arange(-5, 5, 0.25)
>>> X, Y = np.meshgrid(X, Y)
>>> R = np.sqrt(X**2 + Y**2)
>>> Z = np.sin(R)
>>> surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
...                        linewidth=0, antialiased=False)
>>> ax.set_zlim(-1.01, 1.01)
(-1.01, 1.01)
>>> ax.zaxis.set_major_locator(LinearLocator(10))
>>> ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
>>> fig.colorbar(surf, shrink=0.5, aspect=5)
<matplotlib.colorbar.Colorbar object at 0x028F86B0>
>>> plt.show()




Scatter plots

Axes3D.scatter(xsyszs=0zdir='z's=20c=Nonedepthshade=True*args**kwargs)
Create a scatter plot.
ArgumentDescription
xsysPositions of data points.
zsEither an array of the same length as xs and ys or a single value to place all points in the same plane. Default is 0.
zdirWhich direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2D set.
sSize in points^2. It is a scalar or an array of the same length as x and y.
cA color. c can be a single color format string, or a sequence of color specifications of length N, or a sequence of Nnumbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. c can be a 2-D array in which the rows are RGB or RGBA, however, including the case of a single row to specify the same color for all points.
depthshadeWhether or not to shade the scatter markers to give the appearance of depth. Default is True.
Keyword arguments are passed on to scatter().
Returns a Patch3DCollection


'''
==============
3D scatterplot
==============

Demonstration of a basic scatterplot in 3D.
'''

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np


def randrange(n, vmin, vmax):
    '''
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    '''
    return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()



Line plots

Axes3D.plot(xsys*args**kwargs)
Plot 2D or 3D data.
ArgumentDescription
xsysx, y coordinates of vertices
zsz value(s), either one for all points or one for each point.
zdirWhich direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2D set.
Other arguments are passed on to plot()


PARAMETRIC PLOT 3D
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()

plt.show()


Wireframe plots

Axes3D.plot_wireframe(XYZ*args**kwargs)
Plot a 3D wireframe.
The rstride and cstride kwargs set the stride used to sample the input data to generate the graph. If either is 0 the input data in not sampled along this direction producing a 3D line plot rather than a wireframe plot. The stride arguments are only used by default if in the ‘classic’ mode. They are now superseded by rcount and ccount. Will raise ValueError if both stride and count are used.
` The rcount and ccount kwargs supersedes rstride and
cstride for default sampling method for wireframe plotting. These arguments will determine at most how many evenly spaced samples will be taken from the input data to generate the graph. This is the default sampling method unless using the ‘classic’ style. Will raise ValueError if both stride and count are specified. If either is zero, then the input data is not sampled along this direction, producing a 3D line plot rather than a wireframe plot. Added in v2.0.0.
ArgumentDescription
XY,Data values as 2D arrays
Z
rstrideArray row stride (step size), defaults to 1
cstrideArray column stride (step size), defaults to 1
rcountUse at most this many rows, defaults to 50
ccountUse at most this many columns, defaults to 50

'''
=================
3D wireframe plot
=================

A very basic demonstration of a wireframe plot.
'''

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Grab some test data.
X, Y, Z = axes3d.get_test_data(0.05)

# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()




'''
========================
3D surface (solid color)
========================

Demonstrates a very basic plot of a 3D surface using a solid color.
'''

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Make data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

# Plot the surface
ax.plot_surface(x, y, z, color='b')

plt.show()





UPDATED FOR AMZN STOCK 1-2021





import numpy as np
import matplotlib.pyplot as plt

points = np.array([
(197,3116.2),
(198,3103.0),
(199,3156.1),
(200,3078.1),
(201,3008.7),
(202,2954.9),
(203,2960.5),
(204,3129.0),
(205,2999.9),
(206,3019.8),
(207,3095.1),
(208,3174.1),
(209,3144.9),
(210,3148.7),
(211,3221.3),
(212,3125.0),
(213,3199.2),
(214,3100.0),
(215,3195.7),
(216,3190.6),
(217,3286.6),
(218,3442.9),
(219,3443.6),
(220,3363.7),
(221,3338.6),
(222,3272.7),
(223,3207.2),
(224,3217.0),
(225,3184.9),
(226,3176.4),
(227,3204.4),
(228,3207.0),
(229,3286.3),
(230,3162.8),
(231,3211.0),
(232,3036.1),
(233,3004.5),
(234,3048.4),
(235,3241.2),
(236,3322.0),
(237,3311.4),
(238,3143.7),
(239,3035.0),
(240,3137.4),
(241,3110.3),
(242,3128.8),
(243,3131.1),
(244,3135.7),
(245,3105.5),
(246,3117.0),
(247,3099.4),
(248,3098.4),
(249,3118.1),
(250,3185.1),
(251,3195.3),
(252,3168.0),
(253,3220.1),
(254,3203.5),
(255,3186.7),
(256,3162.6),
(257,3158.0),
(258,3177.3),
(259,3104.2),
(260,3101.5),
(261,3116.4),
(262,3157.0),
(263,3165.1),
(264,3241.0),
(265,3236.1),
(266,3201.6),
(267,3206.2),
(268,3206.5),
(269,3185.3),
(270,3172.7),
(271,3284.0),
(272,3322.0),
(273,3285.9),
(274,3256.9),
(275,3186.6),
(276,3218.5)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()








lunes, 3 de julio de 2017

PIP in python and How to install matplotlib on Windows PC

If you're using this information and don't leave a comment, then you're a lammer. A LAMMER

cambiar las variables de entorno

al PATH

C:\Users\rober\AppData\Local\Programs\Python\Python35\Scripts\;C:\Users\rober\AppData\Local\Programs\Python\Python35\

C:\Users\rober\AppData\Local\Programs\Python\Python35\Scripts\;C:\Users\rober\AppData\Local\Programs\Python\Python35\
C:\Users\rober\AppData\Local\Programs\Python\Python35\

PIP




pip es un sistema de gestión de paquetes utilizado para instalar y administrar paquetes de software escritos en Python. Muchos paquetes pueden ser encontrados en el Python Package Index (PyPI). Python 2.7.9 y posteriores (en la serie Python2), Python 3.4 y posteriores incluyen pip (pip3 para Python3) por defecto.
pip es un acrónimo recursivo que se puede interpretar como Pip Instalador de Paquetes o Pip Instalador de Python.

Interfaz línea de comando[editar]


Salida de pip install virtualenv
Una ventaja importante de pip es la facilidad de su interfaz de línea de comandos, el cual permite instalar paquetes de software de Python fácilmente desde solo una orden:
pip install nombre-paquete
Los usuarios también pueden fácilmente desinstalar algún paquete:
pip uninstall nombre-paquete
Otra característica particular de pip es que permite gestionar listas de paquetes y sus números de versión correspondientes a través de un archivo de requisitos. Esto nos permite una recreación eficaz de un conjunto de paquetes en un entorno separado (p. ej. otro ordenador) o entorno virtual. Esto se puede conseguir con un archivo correctamente formateado requisitos.txt y la siguiente orden:
pip install -r requisitos.txt
Con pip es posible instalar un paquete para una versión concreta de Python, sólo es necesario reemplazar ${versión} por la versión de Python que queramos: 2, 3, 3.4, etc:
pip${versión} install nombre-paquete

Uso de servicio del alojamiento web[editar]

Pip es usado para soporte de Python en la nube, como por Heroku.


How to install matplotlib on Windows PC
Install matplotlib in Windows
Matplotlib es una biblioteca para la generación de gráficos a partir de datos contenidos en listas o arrays en el lenguaje de programación Python y su extensión matemática NumPy. Proporciona una API, pylab, diseñada para recordar a la de MATLAB.

I presume that you have already installed python in your PC and added it to system path. And now you want to install one of the best plotting library matplotlib. It is pretty straightforward in a linux-based OS with a package manager. But in Windows –
1) Install distribute: It helps in installing python packages easily. Download file, open windows command prompt or powershell and using ‘cd’ command change to the folder containing the downloaded file, then perform the following command to install distribute –
1
python distribute_setup.py
2) Add easy-install to system PATH: We have to add the Scripts directory to the system path. If you have python 3.3, the path to the Scripts directory is C:\Python33\Scripts\ The method of adding a directory to system path has already shown in the previous tutorial.
3) Install matplotlib: There are certain dependencies needed to be installed for matplotlib working correctly. But these are no more our concern. The distribute package will check for dependencies and install it automatically. We just have to run this command –
1
easy_install matplotlib
Voila! We have successfully installed matplotlib.
4) Test it: Now start python interpreter and run the following commands to test the plotting library –
1
2
3
4
5
6
>> import pylab
>> x = [i/10 for i in range(0, 100)]
>> y = [i*i for i in x]
>> pylab.plot(x, y)
[...]
>> pylab.show()


Dibuja la grafica del coseno, usando pycharms on mathplotlib ejemplo de wiki







Output of the last command is the following plot – figure 1
C:\WINDOWS\system32>python -m pip install -U pip

C:\WINDOWS\system32>pip install scipy

C:\WINDOWS\system32>pip install numpy


NumPy

NumPy is the fundamental package for scientific computing with Python. It contains among other things:
  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.
NumPy is licensed under the BSD license, enabling reuse with few restrictions.
NumPy es una extensión de Python, que le agrega mayor soporte para vectores y matrices, constituyendo una biblioteca de funciones matemáticas de alto nivel para operar con esos vectores o matrices. El ancestro de NumPy, Numeric, fue creado originalmente por Jim Hugunin con algunas contribuciones de otros desarrolladores. En 2005, Travis Oliphant creó NumPy incorporando características de Numarray en NumPy con algunas modificaciones. NumPy es open source.

Ejemplo[editar]

El siguiente es un ejemplo de como manipula vectores y los dibuja en un gráfico usando Matplotlib.
import numpy
from matplotlib import pyplot
x = numpy.linspace(0, 2 * numpy.pi, 100)
y = numpy.sin(x)
pyplot.plot(x, y)
pyplot.show()

SciPy es una biblioteca open source de herramientas y algoritmos matemáticos para Python que nació a partir de la colección original de Travis Oliphant que consistía de módulos de extensión para Python, lanzada en 1999 bajo el nombre de Multipack (llamada por los paquetes netlib que reunían a ODEPACK, QUADPACK, y MINPACK).
SciPy contiene módulos para optimizaciónálgebra linealintegracióninterpolaciónfunciones especialesFFTprocesamiento de señales y de imagen, resolución de ODEs y otras tareas para la ciencia e ingeniería. Está dirigida al mismo tipo de usuarios que los de aplicaciones como MATLABGNU Octave, y Scilab.

Véase también[editar]

  • NumPy (Biblioteca que da soporte para vectores y matrices, para trabajar con algoritmos de alto nivel)
  • SymPy (Biblioteca que define Objetos de tipo formula)
  • Matplotlib (Biblioteca que define la Representación de funciones matemáticas en diferentes tipos de gráficas)
  • Jupyter Notebook (Programa para análisis científico, y programación en linea) <- Pagina en contruccion


MANUAL DE PLOTEO EN PYTHON  MATPLOTLIB



>>> import pylab

>>> x = [i/10 for i in range(0,100)]

>>> y= [i*i for i in x]

>>> pylab.plot

<function plot at 0x000001D4CB074488>
>>> pylab.plot(x,y)
[<matplotlib.lines.Line2D object at 0x000001D4CCD53940>]
>>> pylab.show()

>>> import numpy
>>> from matplotlib import pyplot
>>> x= numpy.linspace(0, 2*numpy.pi, 100)
>>> y = numpy.sin(x)
>>> pyplot.plot(x,y)
[<matplotlib.lines.Line2D object at 0x000001D4CB89AF98>]
>>> pyplot.show()


EJEMPLO2 











import matplotlib.pyplot as plt

x = range(100)
y = range(100,200)
fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first')
ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label='second')
plt.legend(loc='upper left');
plt.show()
enter image description here

Pyplot tutorial

matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc. In matplotlib.pyplot various states are preserved across function calls, so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that “axes” here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
../_images/pyplot_simple.png
You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you provide a single list or array to the plot() command, matplotlib assumes it is a sequence of y values, and automatically generates the x values for you. Since python ranges start with 0, the default x vector has the same length as y but starts with 0. Hence the x data are [0,1,2,3].
plot() is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
For every x, y pair of arguments, there is an optional third argument which is the format string that indicates the color and line type of the plot. The letters and symbols of the format string are from MATLAB, and you concatenate a color string with a line style string. The default format string is ‘b-‘, which is a solid blue line. For example, to plot the above with red circles, you would issue
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()
../_images/pyplot_formatstr.png






See the plot() documentation for a complete list of line styles and format strings. The axis() command in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the viewport of the axes.
If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example below illustrates a plotting several lines with different format styles in one command using arrays.
import numpy as np
import matplotlib.pyplot as plt

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
../_images/pyplot_three.png

Controlling line properties

Lines have many attributes that you can set: linewidth, dash style, antialiased, etc; see matplotlib.lines.Line2D. There are several ways to set line properties
  • Use keyword args:
    plt.plot(x, y, linewidth=2.0)
    
  • Use the setter methods of a Line2D instance. plot returns a list of Line2D objects; e.g., line1, line2 = plot(x1, y1, x2, y2). In the code below we will suppose that we have only one line so that the list returned is of length 1. We use tuple unpacking with line, to get the first element of that list:
    line, = plt.plot(x, y, '-')
    line.set_antialiased(False) # turn off antialising
    
  • Use the setp() command. The example below uses a MATLAB-style command to set multiple properties on a list of lines. setp works transparently with a list of objects or a single object. You can either use python keyword arguments or MATLAB-style string/value pairs:
    lines = plt.plot(x1, y1, x2, y2)
    # use keyword args
    plt.setp(lines, color='r', linewidth=2.0)
    # or MATLAB style string value pairs
    plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
    
Here are the available Line2D properties.
PropertyValue Type
alphafloat
animated[True | False]
antialiased or aa[True | False]
clip_boxa matplotlib.transform.Bbox instance
clip_on[True | False]
clip_patha Path instance and a Transform instance, a Patch
color or cany matplotlib color
containsthe hit testing function
dash_capstyle['butt' | 'round' | 'projecting']
dash_joinstyle['miter' | 'round' | 'bevel']
dashessequence of on/off ink in points
data(np.array xdata, np.array ydata)
figurea matplotlib.figure.Figure instance
labelany string
linestyle or ls'-' | '--' | '-.' | ':' | 'steps' | ...]
linewidth or lwfloat value in points
lod[True | False]
marker'+' | ',' | '.' | '1' | '2' | '3' | '4' ]
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markersize or msfloat
markevery[ None | integer | (startind, stride) ]
pickerused in interactive line selection
pickradiusthe line pick selection radius
solid_capstyle['butt' | 'round' | 'projecting']
solid_joinstyle['miter' | 'round' | 'bevel']
transforma matplotlib.transforms.Transform instance
visible[True | False]
xdatanp.array
ydatanp.array
zorderany number
To get a list of settable line properties, call the setp() function with a line or lines as argument
In [69]: lines = plt.plot([1, 2, 3])

In [70]: plt.setp(lines)
  alpha: float
  animated: [True | False]
  antialiased or aa: [True | False]
  ...snip

Working with multiple figures and axes

MATLAB, and pyplot, have the concept of the current figure and the current axes. All plotting commands apply to the current axes. The function gca() returns the current axes (a matplotlib.axes.Axes instance), and gcf() returns the current figure (matplotlib.figure.Figure instance). Normally, you don’t have to worry about this, because it is all taken care of behind the scenes. Below is a script to create two subplots.
import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
../_images/pyplot_two_subplots.png
The figure() command here is optional because figure(1) will be created by default, just as a subplot(111) will be created by default if you don’t manually specify any axes. The subplot() command specifies numrows, numcols, fignum where fignum ranges from 1 tonumrows*numcols. The commas in the subplot command are optional if numrows*numcols<10. So subplot(211) is identical to subplot(2, 1, 1). You can create an arbitrary number of subplots and axes. If you want to place an axes manually, i.e., not on a rectangular grid, use the axes()command, which allows you to specify the location as axes([left, bottom, width, height]) where all values are in fractional (0 to 1) coordinates. See pylab_examples example code: axes_demo.py for an example of placing axes manually and pylab_examples example code: subplots_demo.py for an example with lots of subplots.
You can create multiple figures by using multiple figure() calls with an increasing figure number. Of course, each figure can contain as many axes and subplots as your heart desires:
import matplotlib.pyplot as plt
plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])


plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title
You can clear the current figure with clf() and the current axes with cla(). If you find it annoying that states (specifically the current image, figure and axes) are being maintained for you behind the scenes, don’t despair: this is just a thin stateful wrapper around an object oriented API, which you can use instead (see Artist tutorial)
If you are making lots of figures, you need to be aware of one more thing: the memory required for a figure is not completely released until the figure is explicitly closed with close(). Deleting all references to the figure, and/or using the window manager to kill the window in which the figure appears on the screen, is not enough, because pyplot maintains internal references until close() is called.

Working with text

The text() command can be used to add text in an arbitrary location, and the xlabel()ylabel() and title() are used to add text in the indicated locations (see Text introduction for a more detailed example)
import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)


plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
../_images/pyplot_text.png
All of the text() commands return an matplotlib.text.Text instance. Just as with with lines above, you can customize the properties by passing keyword arguments into the text functions or using setp():
t = plt.xlabel('my data', fontsize=14, color='red')
These properties are covered in more detail in Text properties and layout.

Using mathematical expressions in text

matplotlib accepts TeX equation expressions in any text expression. For example to write the expression  in the title, you can write a TeX expression surrounded by dollar signs:
plt.title(r'$\sigma_i=15$')
The r preceding the title string is important – it signifies that the string is a raw string and not to treat backslashes as python escapes. matplotlib has a built-in TeX expression parser and layout engine, and ships its own math fonts – for details see Writing mathematical expressions. Thus you can use mathematical text across platforms without requiring a TeX installation. For those who have LaTeX and dvipng installed, you can also use LaTeX to format your text and incorporate the output directly into your display figures or saved postscript – see Text rendering With LaTeX.

Annotating text

The uses of the basic text() command above place text at an arbitrary position on the Axes. A common use for text is to annotate some feature of the plot, and the annotate() method provides helper functionality to make annotations easy. In an annotation, there are two points to consider: the location being annotated represented by the argument xy and the location of the text xytext. Both of these arguments are (x,y) tuples.
import numpy as np
import matplotlib.pyplot as plt

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )

plt.ylim(-2,2)
plt.show()
../_images/pyplot_annotate.png
In this basic example, both the xy (arrow tip) and xytext locations (text location) are in data coordinates. There are a variety of other coordinate systems one can choose – see Basic annotation and Advanced Annotation for details. More examples can be found in pylab_examples example code: annotation_demo.py.

Logarithmic and other nonlinear axes

matplotlib.pyplot supports not only linear axis scales, but also logarithmic and logit scales. This is commonly used if data spans many orders of magnitude. Changing the scale of an axis is easy:
plt.xscale(‘log’)
An example of four plots with the same data and different scales for the y axis is shown below.
import numpy as np
import matplotlib.pyplot as plt

from matplotlib.ticker import NullFormatter  # useful for `logit` scale

# Fixing random state for reproducibility
np.random.seed(19680801)

# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

# plot with various axes scales
plt.figure(1)

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)


# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)


# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca().yaxis.set_minor_formatter(NullFormatter())
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)

plt.show()
../_images/pyplot_scales.png



UPDATE 2021






import numpy as np
import matplotlib.pyplot as plt
plt.show()




import numpy as np
import matplotlib.pyplot as plt

points = np.array([
(197,3116.2),
(198,3103.0),
(199,3156.1),
(200,3078.1),
(201,3008.7),
(202,2954.9),
(203,2960.5),
(204,3129.0),
(205,2999.9),
(206,3019.8),
(207,3095.1),
(208,3174.1),
(209,3144.9),
(210,3148.7),
(211,3221.3),
(212,3125.0),
(213,3199.2),
(214,3100.0),
(215,3195.7),
(216,3190.6),
(217,3286.6),
(218,3442.9),
(219,3443.6),
(220,3363.7),
(221,3338.6),
(222,3272.7),
(223,3207.2),
(224,3217.0),
(225,3184.9),
(226,3176.4),
(227,3204.4),
(228,3207.0),
(229,3286.3),
(230,3162.8),
(231,3211.0),
(232,3036.1),
(233,3004.5),
(234,3048.4),
(235,3241.2),
(236,3322.0),
(237,3311.4),
(238,3143.7),
(239,3035.0),
(240,3137.4),
(241,3110.3),
(242,3128.8),
(243,3131.1),
(244,3135.7),
(245,3105.5),
(246,3117.0),
(247,3099.4),
(248,3098.4),
(249,3118.1),
(250,3185.1),
(251,3195.3),
(252,3168.0),
(253,3220.1),
(254,3203.5),
(255,3186.7),
(256,3162.6),
(257,3158.0),
(258,3177.3),
(259,3104.2),
(260,3101.5),
(261,3116.4),
(262,3157.0),
(263,3165.1),
(264,3241.0),
(265,3236.1),
(266,3201.6),
(267,3206.2),
(268,3206.5),
(269,3185.3),
(270,3172.7),
(271,3284.0),
(272,3322.0),
(273,3285.9),
(274,3256.9),
(275,3186.6),
(276,3218.5)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()

zen consultora

Blogger Widgets