  <?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
               xmlns:atom="http://www.w3.org/2005/Atom"
               xmlns:dc="http://purl.org/dc/elements/1.1/"
               xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
               xmlns:admin="http://webns.net/mvcb/"
               xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
               xmlns:content="http://purl.org/rss/1.0/modules/content/">
            <channel>
                <title>
					                		Visualización de datos simple con Python y Matplotlib - Machine Learning                                    </title>
                <link>https://aichallenge.utec.edu.uy/community/machine-learning/visualizacion-de-datos-simple-con-python-y-matplotlib/</link>
                <description>Comunidad de AI de UTEC</description>
                <language>es</language>
                <lastBuildDate>Wed, 11 Mar 2026 06:37:40 +0000</lastBuildDate>
                <generator>wpForo</generator>
                <ttl>60</ttl>
                					                    <item>
                        <title>Visualización de datos simple con Python y Matplotlib</title>
                        <link>https://aichallenge.utec.edu.uy/community/machine-learning/visualizacion-de-datos-simple-con-python-y-matplotlib/#post-121</link>
                        <pubDate>Thu, 18 Mar 2021 20:10:47 +0000</pubDate>
                        <description><![CDATA[Python cuenta con una gran cantidad de librerías las cuales son útiles para trabajar con datos, ya sea para organizarlos, operar con ellos, o visualizarlos. 
 
Para trabajar con datos en f...]]></description>
                        <content:encoded><![CDATA[<p style="text-align: center"><span style="font-weight: 400">Python cuenta con una gran cantidad de librerías las cuales son útiles para trabajar con datos, ya sea para organizarlos, operar con ellos, o visualizarlos. </span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><span style="font-weight: 400">Para trabajar con datos en forma de tablas tenemos </span><a href="https://pandas.pydata.org/"><span style="font-weight: 400">Pandas</span></a><span style="font-weight: 400">, para trabajar matemáticamente con datos numéricamente siempre es recomendable </span><a href="https://numpy.org/"><span style="font-weight: 400">Numpy </span></a><span style="font-weight: 400">y para visualizar datos tenemos </span><a href="https://matplotlib.org"><span style="font-weight: 400">Matplotlib</span></a><span style="font-weight: 400">.</span></p>
<p style="text-align: center"> </p>
<h2 style="text-align: center"><span style="font-weight: 400">Ok ¿Pero que es una librería?</span></h2>
<p style="text-align: center"><span style="font-weight: 400">Un proverbio muy común en la programación es “no inventes la rueda”, básicamente refiriéndose a que no es recomendable perder el tiempo intentando inventar por nuestra cuenta una solución que ya fue implementada incontables veces por otras personas y probablemente de formas más eficientes. Muchos veteranos suelen alargar la popular frase diciendo algo similar a “no reinventes la rueda, a menos que quieras aprender más sobre ruedas”, representando una postura más balanceada en el tema. Básicamente significa que la gran mayoría de la</span><span style="font-weight: 400">s veces no es necesario el tener que resolver 100% por nuestra cuenta todos los retos de nuestro proyecto sin ayudarnos con aquello que ya existe, pero puede ser recomendable si queremos aprender más sobre un tema en específico.</span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img54.jpg" /></p>
<p style="text-align: center"><em><span style="font-size: 8pt">Foto por <a href="http://&quot;/photographer/artritris-35562&quot;" target="true">César Pena</a></span></em></p>
<p style="text-align: center"><span style="font-weight: 400">Ahora sí, ¿Qué son las librerías?. Las librerías en palabras sencillas son un conjunto de funciones las cuales pueden ser fácilmente añadidas a nuestro proyecto y utilizadas con tan solo llamarlas. Son extremadamente útiles y es casi imposible hacer un proyecto (o al menos uno que no tome una eternidad) sin utilizar alguna librería. Las librerías entonces representan la versión corta del famoso proverbio, ya que claramente no somos los primeros en pensar que sería útil el utilizar código para representar datos, entonces ¿Para qué sufrir en lugar de sacar provecho a las herramientas que ya existen?</span></p>
<h2 style="text-align: center"><span style="font-weight: 400">¿Qué es matplotlib?</span></h2>
<p style="text-align: center"><span style="font-weight: 400">Matplotlib es una librería de python creada por </span><a href="https://en.wikipedia.org/wiki/John_D._Hunter"><span style="font-weight: 400">Jhon Hunter</span></a><span style="font-weight: 400"> la cual está especialmente diseñada para visualizar datos. Tomando inspiración de </span><a href="https://www.mathworks.com/products/matlab.html"><span style="font-weight: 400">MATLAB </span></a><span style="font-weight: 400">matplotlib trabaja con tres elementos principales: axis (“ejes”), figure (“figura”) y plot (“gráfico” o “cuadro”). Matplotlib tiene varios módulos especializados en distintas áreas como animación o proyección, nosotros trabajaremos con el módulo </span><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot"><span style="font-weight: 400">pyplot</span></a><span style="font-weight: 400">, el cual se especializa en el dibujado de gráficos relativamente simples y es aún más parecido a MATLAB que el resto de la librería.</span></p>
<p style="text-align: center"> </p>
<h3 style="text-align: center"><strong>A tener en cuenta</strong></h3>
<p style="text-align: center"><span style="font-weight: 400">Para ejecutar el código de muestra puedes utilizar </span><a href="http://colab.research.google.com/"><span style="font-weight: 400">Google Colab</span></a><span style="font-weight: 400">, si nunca lo utilizaste antes puedes leer </span><a href="https://aichallenge.utec.edu.uy/community/machine-learning/introduccion-a-google-colaboratory/"><span style="font-weight: 400">este artículo</span></a><span style="font-weight: 400"> donde te explicamos cómo funciona. </span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><strong>Consejo 1</strong><span style="font-weight: 400">: siempre puedes buscar algún ejemplo en internet y luego modificar el código para adaptarlo a tus necesidades. </span><strong>Todo el mundo lo hace</strong><span style="font-weight: 400">, ya que tomaría una gran cantidad de tiempo el verdaderamente dominar todas las herramientas que nos ofrece matplotlib.</span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><strong>Consejo 2</strong><span style="font-weight: 400">: Siempre es recomendable leer la documentación de una librería o herramienta, ya que suelen tener explicaciones a fondo de cómo operan las funciones, además de tutoriales y ejemplos. Matplotlib cumple con esto teniendo una sección de </span><a href="https://matplotlib.org/stable/gallery/index.html"><span style="font-weight: 400">ejemplos </span></a><span style="font-weight: 400">y otra de </span><a href="https://matplotlib.org/stable/tutorials/index.html#"><span style="font-weight: 400">tutoriales</span></a><span style="font-weight: 400">.</span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><strong>Consejo 3</strong><span style="font-weight: 400">: Incluso el mejor programador busca respuestas en internet, es imposible programar un proyecto sin tener que consultar dudas online. Además de eso, ni el mejor tutorial/artículo te enseñará todo lo necesario sobre un tema, por lo que buscar más sobre el tema en internet siempre será necesario.</span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><strong>Consejo 4</strong><span style="font-weight: 400">: este artículo contiene muchos enlaces a otros artículos y tutoriales como sugerencias para aprender más, todos ellos están en inglés. Pero si tienes dificultad con el idioma siempre puedes traducir la página, este enlace te muestra cómo hacerlo en </span><a href="https://support.google.com/chrome/answer/173424?co=GENIE.Platform%3DDesktop&amp;hl=es-419"><span style="font-weight: 400">Google Chrome</span></a><span style="font-weight: 400"> y </span><a href="https://support.mozilla.org/es/kb/como-anadir-traduccion-firefox"><span style="font-weight: 400">este otro</span></a><span style="font-weight: 400"> te muestra cómo hacerlo utilizando Firefox.</span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><strong>Consejo 5</strong><span style="font-weight: 400">: Si quieres aprender de una forma guiada y completa te recomendamos </span><a href="https://www.youtube.com/watch?v=3Xc3CA655Y4"><span style="font-weight: 400">este curso</span></a><span style="font-weight: 400"> gratuito de </span><a href="https://www.freecodecamp.org/"><span style="font-weight: 400">Freecodecamp.org</span></a></p>
<p style="text-align: center"><span style="font-weight: 400"><br /></span><strong>Recordatorio</strong><span style="font-weight: 400">: en matplotlib hay múltiples maneras de obtener el mismo resultado, los ejemplos de este artículo son los que consideramos más sencillos. Intencionalmente evitamos trabajar individualmente con ejes porque eso requiere más líneas de código y trabajo, pero es recomendable y necesario trabajar con ejes para poder hacer visualizaciones más avanzadas. De todas formas no te preocupes, ya que las visualizaciones simples suelen bastar la mayoría de las veces, ya que generalmente trabajamos con datasets simples y ordenados, no con un acelerador de partículas.</span></p>
<p style="text-align: center"><span style="font-weight: 400">El internet está lleno de tutoriales e información de todo tipo, tanta que en algunos momentos se puede hacer difícil de elegir. Por eso luego de cada ejemplo recomendamos algunos tutoriales y ejemplos, así puedes ahorrarte la indecisión. Aparte de todo eso, también recomendamos </span><a href="https://www.datacamp.com/community/tutorials/matplotlib-tutorial-python#anatomy"><span style="font-weight: 400">este tutorial</span></a><span style="font-weight: 400"> una vez hayas terminado de leer este artículo.</span></p>
<h2 style="text-align: center"><span style="font-weight: 400">Aprendiendo mediante ejemplos</span></h2>
<p style="text-align: center"> </p>
<h3 style="text-align: center"><span style="font-weight: 400">Empezando con la gráfica más fácil</span></h3>
<p style="text-align: center"><span style="font-weight: 400">El primer paso para todos estos ejemplos es importar lo necesario. Como ya vimos la librería es enorme, tiene una gran cantidad de módulos y aproximadamente 70.000 líneas de código. Pero nosotros estamos tan sólo interesados en el módulo pyplot. Por eso nuestra primera línea de código será la siguiente:</span></p>
<pre><span style="font-weight: 400;color: #ff00ff">import</span><span style="font-weight: 400"> <span style="color: #99cc00">matplotlib.pyplot</span> </span><span style="font-weight: 400;color: #ff00ff">as</span><span style="font-weight: 400"> plt</span></pre>
<p style="text-align: center"><span style="font-weight: 400"> </span></p>
<p style="text-align: center"><span style="font-weight: 400;color: #ff00ff">import </span><span style="font-weight: 400">sirve para importar cualquier librería, pero si escribiéramos tan solo</span></p>
<pre><span style="font-weight: 400"><span style="color: #ff00ff">import</span> matplotlib<br /><br /></span></pre>
<p style="text-align: center"><span style="font-weight: 400">Estaríamos importando toda la librería incluyendo los módulos que no nos interesan. Agregar el “</span><span style="font-weight: 400">.pyplot</span><span style="font-weight: 400">” nos asegura que solo se va a importar el módulo que queremos. Ahora tenemos todas las funciones del módulo pyplot. Pero para usar cada una de ellas necesitaríamos escribir</span><span style="font-weight: 400"></span></p>
<pre><span style="font-weight: 400">matplotlib.pyplot.NOMBRE_DE_LA_FUNCION()</span>
<span style="font-weight: 400"> </span></pre>
<p style="text-align: center"><span style="font-weight: 400">Lo cual claramente no sería muy cómodo de hacer múltiples veces. Por eso es tan útil agregar </span><span style="font-weight: 400">as</span><span style="font-weight: 400"> plt</span><span style="font-weight: 400"> al final de la línea. El comando </span><span style="font-weight: 400">as</span> <span style="font-weight: 400">nos deja asignarle un “alias” al módulo que importamos. Por lo que ahora para cada función basta con escribir:</span></p>
<pre><span style="font-weight: 400"> </span>
<span style="font-weight: 400">plt.NOMBRE_DE_LA_FUNCION()</span>
<span style="font-weight: 400"> </span></pre>
<p style="text-align: center"><span style="font-weight: 400">La primera función que vamos a utilizar es la función plot, esta función sirve para graficar líneas continuas y es de las más sencillas de utilizar. La función plot sigue la siguiente sintaxis</span></p>
<pre><span style="font-weight: 400"> </span>
<span style="font-weight: 400">plt.plot(ARGUMENTOS) </span><span style="font-weight: 400;color: #99cc00"># Los argumentos se separan por comas</span>
<span style="font-weight: 400"> </span></pre>
<p style="text-align: center"><span style="font-weight: 400">Por lo que vamos a definir dos arrays, cada uno conteniendo un conjunto diferente de números. Estos arrays los pasaremos como argumento a la función plot y eso nos devolverá un gráfica con una línea la cual une todos los puntos, tomando los elementos del conjunto como las coordenadas x e y de los distintos puntos.</span></p>
<pre><span style="font-weight: 400"> </span>
<span style="font-weight: 400;color: #99cc00"># Importamos pyplot como plt</span>
<span style="font-weight: 400;color: #ff00ff">import</span><span style="font-weight: 400"> matplotlib.pyplot </span><span style="font-weight: 400;color: #ff00ff">as</span><span style="font-weight: 400"> plt</span>
<span style="font-weight: 400;color: #99cc00"># creamos dos arrays con distintos conjuntos de datos</span><br /><br /><span style="font-weight: 400">conjunto1 =  </span><span style="font-weight: 400;color: #99cc00"># estos numeros son enteros, por lo que serían elementos int</span><br /><br /><span style="font-weight: 400">conjunto2 =  </span><span style="font-weight: 400;color: #99cc00"># estos numeros tienen decimales, por lo que serian float</span><br /><br /><br /><br /><span style="font-weight: 400;color: #99cc00"># usamos la función plot para generar una linea de acuerdo a los puntos</span><br /><br /><span style="font-weight: 400">plt.plot(conjunto1, conjunto2)</span><br /><br /><br /><br /><span style="font-weight: 400;color: #99cc00"># la función show no es necesaria si estamos usando por ejemplo Google Colab,<br /># pero si puede ser necesaria al usar otros entornos, por lo cual siempre es recomendable escribirla.</span><br /><br /><span style="font-weight: 400;color: #99cc00"># Esta función se asegura de que se muestre nuestra figura</span><br /><br /><span style="font-weight: 400">plt.show()</span></pre>
<p style="text-align: center"> </p>
<p style="text-align: center"><span style="font-weight: 400">Si ejecutas el código anterior deberías obtener la siguiente figura. </span></p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img8.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Previamente mencionamos que matplotlib trabajaba principalmente con tres elementos en sus gráficos. Estos eran axis (“ejes”), figure (“figura”) y plot (“gráfico” o “cuadro”). En nuestra anterior figura podemos identificar los 3.</span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/Elementos-de-la-gráfica.gif" /></p>
<p style="text-align: center"><span style="font-weight: 400">Excelente, ahora veamos qué otras cosas podemos hacer con esta sencilla gráfica.</span></p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/anatomy.jpeg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Esta imagen del sitio oficial de matplotlib nos muestra la anatomía de una figura, vemos que hay una gran cantidad de elementos los cuales podemos personalizar según nuestras necesidades.</span></p>
<p style="text-align: center"><span style="font-weight: 400">Primero que nada vamos a usar nuevamente la función plot para agregar una recta a la figura.</span></p>
<pre><span style="font-weight: 400;color: #99cc00"># usamos la función plot para generar una linea de acuerdo a los puntos</span><br /><br /><span style="font-weight: 400">plt.plot(conjunto1, conjunto2)</span><br /><br /><span style="font-weight: 400">plt.plot(, ) <br /></span><span style="font-weight: 400;color: #99cc00"># Agregamos un segundo ploteo, va a formar una recta entre los puntos (0,0) y (64,3)</span></pre>
<p style="text-align: center"><span style="font-weight: 400">Esto debería resultar en la siguiente figura, donde las dos líneas coinciden en su primeros y últimos puntos.</span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img15.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Ahora vamos a asignarle un nombre a los ejes, un título a la figura y vamos a hacer que sea cuadriculada.</span></p>
<p style="text-align: center"> </p>
<pre><span style="font-weight: 400">plt.title(</span><span style="font-weight: 400;color: #800000">'Gráfica de muestra'</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># Agrego un titulo</span><br /><br /><span style="font-weight: 400">plt.ylabel(</span><span style="font-weight: 400;color: #800000">'Nombre del eje Y'</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># asigno un nombre al eje y</span><br /><br /><span style="font-weight: 400">plt.xlabel(</span><span style="font-weight: 400;color: #800000">'Nombre del eje X'</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># asigno un nombre al eje y</span><br /><br /><span style="font-weight: 400">plt.grid(</span><span style="font-weight: 400;color: #0000ff">True</span><span style="font-weight: 400">)  </span><span style="font-weight: 400;color: #99cc00"># Esto se encarga de que sea cuadriculada la figura</span></pre>
<p style="text-align: center"><span style="font-weight: 400">La figura hasta el momento debería verse así.</span></p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img16.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Pero todavía podemos seguir personalizando esta figura, vamos a cambiar el color de las líneas, el estilo de las mismas, agregar una leyenda. Para esto será necesario agregar algunas cosas a nuestras funciones de plot. Vamos a agregar el argumento label a cada una de las funciones plot, también vamos a agregar el argumento color para cambiar el color de cada línea y además el argumento linestyle para cambiar el estilo de la línea.</span></p>
<pre><span style="font-weight: 400">plt.plot(conjunto1,conjunto2,label=</span><span style="font-weight: 400;color: #800000">'Caso 1'</span><span style="font-weight: 400">,linestyle=</span><span style="font-weight: 400;color: #800000">'dotted'</span><span style="font-weight: 400">,color=</span><span style="font-weight: 400;color: #800000">'green'</span><span style="font-weight: 400">) <br /></span><span style="font-weight: 400;color: #99cc00"># dotted nos da una linea punteada</span><br /><br /><br /><br /><br /><span style="font-weight: 400">plt.plot(,,label=</span><span style="font-weight: 400;color: #800000">'Caso 2'</span><span style="font-weight: 400">,linestyle=</span><span style="font-weight: 400;color: #800000">'dashed'</span><span style="font-weight: 400">,color=</span><span style="font-weight: 400;color: #800000">'red'</span><span style="font-weight: 400">)<br /></span><span style="font-weight: 400;color: #99cc00"># dashed nos da una linea hecha de lineas mas pequeñas</span><br /><br /><br /><span style="font-weight: 400">plt.legend() <br /></span><span style="font-weight: 400;color: #99cc00"># la funcion legend se encarga de mostrar la leyenda en la figura, <br />#esto lo hace leyendo los atributos label de cada plot<br /><br /></span></pre>
<p style="text-align: center"><span style="font-weight: 400">También vamos a definir el tamaño de la figura en general así como el tamaño de la fuente en los ejes. Para eso usaremos la función figure con el argumento figsize.</span></p>
<pre><span style="font-weight: 400">plt.figure(figsize=(</span><span style="font-weight: 400">5</span><span style="font-weight: 400">,</span><span style="font-weight: 400">5</span><span style="font-weight: 400">)) </span><span style="font-weight: 400;color: #99cc00">#Definimos un tamaño para la gráfica<br /><br /></span></pre>
<p style="text-align: center"><span style="font-weight: 400">Y agregamos el atributo fontsize a xlabel y ylabel</span></p>
<pre><span style="font-weight: 400">plt.ylabel(</span><span style="font-weight: 400;color: #800000">'Nombre del eje Y'</span><span style="font-weight: 400">, fontsize=</span><span style="font-weight: 400">12</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># asigno un nombre al eje y</span><br /><br /><span style="font-weight: 400">plt.xlabel(</span><span style="font-weight: 400;color: #800000">'Nombre del eje X'</span><span style="font-weight: 400">, fontsize=</span><span style="font-weight: 400">12</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># asigno un nombre al eje y<br /></span></pre>
<p style="text-align: center"> </p>
<p style="text-align: center"><span style="font-weight: 400">Nuestro código final debería ser el siguiente:</span></p>
<pre><span style="font-weight: 400;color: #99cc00"><br /></span><br /><br /><span style="font-weight: 400;color: #99cc00"># Importamos pyplot como plt</span><br /><br /><span style="font-weight: 400;color: #ff00ff">import</span><span style="font-weight: 400"> matplotlib.pyplot </span><span style="font-weight: 400;color: #ff00ff">as</span><span style="font-weight: 400"> plt</span><br /><br /><br /><span style="font-weight: 400;color: #99cc00"># creamos dos arrays con distintos conjuntos de datos</span><br /><br /><span style="font-weight: 400">conjunto1 =  </span><span style="font-weight: 400;color: #99cc00"># estos numeros son enteros, por lo que serían elementos int</span><br /><br /><span style="font-weight: 400">conjunto2 =  </span><span style="font-weight: 400"># estos numeros tienen decimales, por lo que serian float</span><br /><br /><span style="font-weight: 400">plt.figure(figsize=(</span><span style="font-weight: 400">5</span><span style="font-weight: 400">,</span><span style="font-weight: 400">5</span><span style="font-weight: 400">)) </span><span style="font-weight: 400">#Definimos un tamaño para la gráfica</span><br /><br /><br /><span style="font-weight: 400;color: #99cc00"># usamos la función plot para generar una linea de acuerdo a los puntos</span><br /><br /><span style="font-weight: 400">plt.plot(conjunto1, conjunto2, label=</span><span style="font-weight: 400;color: #800000">'Caso 1'</span><span style="font-weight: 400">, linestyle=</span><span style="font-weight: 400;color: #800000">'dotted'</span><span style="font-weight: 400">, color=</span><span style="font-weight: 400;color: #800000">'green'</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># dotted nos da una linea punteada</span><br /><br /><span style="font-weight: 400">plt.plot(, , label=</span><span style="font-weight: 400;color: #800000">'Caso 2'</span><span style="font-weight: 400">, linestyle=</span><span style="font-weight: 400;color: #800000">'dashed'</span><span style="font-weight: 400">, color=</span><span style="font-weight: 400;color: #800000">'red'</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># dashed nos da una linea hecha de lineas mas pequeñas</span><br /><br /><span style="font-weight: 400">plt.legend() </span><span style="font-weight: 400;color: #99cc00"># la funcion legend se encarga de mostrar la leyenda en la figura, esto lo hace leyendo los atributos label de cada plot</span><br /><br /><span style="font-weight: 400">plt.title(</span><span style="font-weight: 400;color: #800000">'Gráfica de muestra'</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># Agrego un titulo</span><br /><br /><span style="font-weight: 400">plt.ylabel(</span><span style="font-weight: 400;color: #800000">'Nombre del eje Y'</span><span style="font-weight: 400">, fontsize=</span><span style="font-weight: 400">12</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># asigno un nombre al eje y</span><br /><br /><span style="font-weight: 400">plt.xlabel(</span><span style="font-weight: 400;color: #800000">'Nombre del eje X'</span><span style="font-weight: 400">, fontsize=</span><span style="font-weight: 400">12</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># asigno un nombre al eje X</span><br /><br /><span style="font-weight: 400">plt.grid(</span><span style="font-weight: 400;color: #0000ff">True</span><span style="font-weight: 400">)  </span><span style="font-weight: 400;color: #99cc00"># Esto se encarga de que sea cuadriculada la figura</span><br /><br /><span style="font-weight: 400;color: #99cc00"># la función show no es necesaria si estamos usando por ejemplo Google Colab, pero si puede ser necesaria al usar otros entornos, por lo cual siempre es recomendable escribirla.</span><br /><br /><span style="font-weight: 400;color: #99cc00"># Esta función se asegura de que se muestre nuestra figura</span><br /><br /><span style="font-weight: 400">plt.show()</span><br /><br /><span style="font-weight: 400;color: #99cc00"><br /></span></pre>
<p style="text-align: center"><span style="font-weight: 400">Y la figura debería verse así.</span></p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img21.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Es importante recordar que con matplotlib hay muchas maneras de obtener el mismo resultado, la idea de este artículo es presentar la forma que nos parece más sencilla para un principiante. Por ejemplo, estas dos líneas de código consiguen el mismo resultado:</span></p>
<p style="text-align: center"> </p>
<pre><span style="font-weight: 400">plt.plot(conjunto1, conjunto2, linestyle=</span><span style="font-weight: 400;color: #800000">'dashed'</span><span style="font-weight: 400">, color=</span><span style="font-weight: 400;color: #800000">'green'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.plot(conjunto1, conjunto2, </span><span style="font-weight: 400;color: #800000">'g--'</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00"># g indica que el color es green, mientras ‘--’ indica que la línea estilo dashed</span><br /><br /></pre>
<p style="text-align: center"><span style="font-weight: 400">Pero para un principiante probablemente la primera sea más fácil de entender. Lo importante es entender los principios básicos para luego poder construir encima de esa base. </span></p>
<p style="text-align: center"><span style="font-weight: 400">Para ver más sobre gráficas de líneas te recomendamos </span><a href="https://pythonspot.com/matplotlib-line-chart/"><span style="font-weight: 400">este tutorial</span></a><span style="font-weight: 400"> o </span><a href="https://www.tutorialspoint.com/matplotlib/matplotlib_simple_plot.htm"><span style="font-weight: 400">este otro</span></a><span style="font-weight: 400">, además de los </span><a href="https://matplotlib.org/stable/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py"><span style="font-weight: 400">ejemplos de matplotlib.org.</span></a></p>
<h3> </h3>
<h3 style="text-align: center"><span style="font-weight: 400;font-size: 14pt">Ejemplo de gráfico de dispersión simple</span></h3>
<pre><span style="font-weight: 400">La función scatter nos permite graficar nubes de puntos.</span><br /><br /><span style="font-weight: 400;color: #99cc00"># Importamos pyplot como plt</span><br /><span style="font-weight: 400;color: #ff00ff">import</span><span style="font-weight: 400"> matplotlib.pyplot </span><span style="font-weight: 400;color: #ff00ff">as</span><span style="font-weight: 400"> plt</span><br /><span style="font-weight: 400;color: #ff00ff">import</span><span style="font-weight: 400"> numpy </span><span style="font-weight: 400;color: #ff00ff">as</span><span style="font-weight: 400"> np </span><span style="font-weight: 400;color: #99cc00"># Importamos numpy para poder generar numeros aleatorios</span><br /><br /><span style="font-weight: 400;color: #99cc00">#Vamos a generar 100 puntos</span><br /><span style="font-weight: 400">N = </span><span style="font-weight: 400;color: #008000">100</span><br /><br /><span style="font-weight: 400;color: #99cc00"># Generamos 100 coordenadas de X</span><br /><span style="font-weight: 400">x = np.random.rand(N)</span><br /><br /><span style="font-weight: 400;color: #99cc00"># Generamos 100 coordenadas de y</span><br /><span style="font-weight: 400">y = np.random.rand(N)</span><br /><br /><span style="font-weight: 400;color: #99cc00"># Repetimos lo mismo con otras variables</span><br /><span style="font-weight: 400">x1 = np.random.rand(N)</span><br /><span style="font-weight: 400">y1 = np.random.rand(N)</span><br /><br /><span style="font-weight: 400;color: #99cc00"># Graficamos x e y como nube de puntos</span><br /><span style="font-weight: 400">plt.scatter(x,y, color=</span><span style="font-weight: 400;color: #800000">'orange'</span><span style="font-weight: 400">, alpha=</span><span style="font-weight: 400;color: #008000">0.5</span><span style="font-weight: 400">, label = </span><span style="font-weight: 400;color: #800000">'puntos naranjas'</span><span style="font-weight: 400">) </span><br /><br /><span style="font-weight: 400;color: #99cc00"># alpha = 0.5 hace que los puntos sean 50% transparentes</span><br /><br /><br /><span style="font-weight: 400">plt.scatter(x1,y1, color=</span><span style="font-weight: 400;color: #800000">'blue'</span><span style="font-weight: 400">, alpha=</span><span style="font-weight: 400;color: #008000">0.5</span><span style="font-weight: 400">, label = </span><span style="font-weight: 400;color: #800000">'puntos azules'</span><span style="font-weight: 400">)</span><br /><span style="font-weight: 400">plt.legend()</span><br /><span style="font-weight: 400">plt.show() </span><span style="font-weight: 400;color: #99cc00">#siempre recomendable la funcion show</span><br /><br /></pre>
<p style="text-align: center"><span style="font-weight: 400">Resultado<br /><br /></span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img26.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Para ver más sobre gráficas de dispersión te recomendamos </span><a href="https://pythonspot.com/matplotlib-scatterplot/"><span style="font-weight: 400">este tutorial</span></a><span style="font-weight: 400"> o </span><a href="https://www.tutorialspoint.com/matplotlib/matplotlib_scatter_plot.htm"><span style="font-weight: 400">este otro</span></a><span style="font-weight: 400">, además de los </span><a href="https://matplotlib.org/stable/gallery/misc/hyperlinks_sgskip.html#sphx-glr-gallery-misc-hyperlinks-sgskip-py"><span style="font-weight: 400">ejemplos de matplotlib.org</span></a><span style="font-weight: 400">. </span></p>
<h3> </h3>
<h3 style="text-align: center"><span style="font-weight: 400;font-size: 14pt">Ejemplo de Histograma</span></h3>
<p style="text-align: center"><span style="font-weight: 400">Un histograma nos permite ver la frecuencia de repetición de un elemento en un conjunto. Son vitales para la visualización y análisis de datos.</span></p>
<p style="text-align: center"> </p>
<pre><span style="font-weight: 400;color: #99cc00"># Importamos pyplot como plt</span><br /><br /><span style="font-weight: 400">import</span><span style="font-weight: 400"> matplotlib.pyplot </span><span style="font-weight: 400">as</span><span style="font-weight: 400"> plt</span><br /><br /><span style="font-weight: 400">import</span><span style="font-weight: 400"> numpy </span><span style="font-weight: 400">as</span><span style="font-weight: 400"> np </span><span style="font-weight: 400;color: #99cc00"># Importamos numpy para operar con numeros</span><br /><br /><br /><span style="font-weight: 400;color: #99cc00">#Vamos a generar 100 numeros aleatorios</span><br /><br /><span style="font-weight: 400">N = </span><span style="font-weight: 400">100</span><br /><br /><br /><span style="font-weight: 400;color: #99cc00"># Guardamos en x los numeros</span><br /><br /><span style="font-weight: 400">x = np.random.rand(N)*</span><span style="font-weight: 400;color: #008080">10</span><br /><br /><span style="font-weight: 400">plt.figure(figsize=(</span><span style="font-weight: 400;color: #008080">10</span><span style="font-weight: 400">,</span><span style="font-weight: 400;color: #008080">5</span><span style="font-weight: 400">)) </span><span style="font-weight: 400;color: #99cc00">#le damos un buen tamano a la figura</span><br /><br /><span style="font-weight: 400">x_ticks = np.arange(</span><span style="font-weight: 400;color: #008080">0</span><span style="font-weight: 400">, </span><span style="font-weight: 400;color: #008080">10</span><span style="font-weight: 400">, </span><span style="font-weight: 400;color: #008080">1</span><span style="font-weight: 400">) </span><span style="font-weight: 400;color: #99cc00">#  la funcion arange de numpy devuelve una lista de numeros</span><br /><br /><span style="font-weight: 400;color: #99cc00"># arange funciona asi arange(numero_inicial, numero_final, numero_pasos), por lo que (0,10,1) devuelve 0,1,2,3,4,5,6,7,8,9,10</span><br /><br /><span style="font-weight: 400;color: #99cc00"># Ingresar (0,10,2) devolveria 0,2,4,6,8,10, mientras que (0,15,5) devolveria 0,5,10,15</span><br /><br /><br /><span style="font-weight: 400">plt.xticks(x_ticks) </span><span style="font-weight: 400;color: #99cc00"># defino que numeros quiero en mi eje x</span><br /><br /><span style="font-weight: 400">plt.hist(x) </span><span style="font-weight: 400;color: #99cc00"># Uso la funcion de histograma para ver cual es el numero que mas se repite en el array X, es decir, su frecuencia</span><br /><br /><br /><span style="font-weight: 400">plt.xlabel(</span><span style="font-weight: 400;color: #800000">'Numero'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.ylabel(</span><span style="font-weight: 400;color: #800000">'Frecuencia'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.title(</span><span style="font-weight: 400;color: #800000">'Ejemplo de histograma'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.show()</span></pre>
<p style="text-align: center"> </p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img31.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Para ver más sobre histogramas te recomendamos </span><a href="https://pythonspot.com/matplotlib-histogram/"><span style="font-weight: 400">este tutorial</span></a><span style="font-weight: 400"> o </span><a href="https://stackabuse.com/matplotlib-histogram-plot-tutorial-and-examples/"><span style="font-weight: 400">este otro</span></a><span style="font-weight: 400">, además de los </span><a href="https://matplotlib.org/stable/gallery/statistics/hist.html"><span style="font-weight: 400">ejemplos de matplotlib.org</span></a><span style="font-weight: 400">.</span></p>
<p style="text-align: center"> </p>
<h3 style="text-align: center"><span style="font-weight: 400;font-size: 14pt">Ejemplo de gráfico de barras</span></h3>
<p style="text-align: center"> </p>
<p style="text-align: center"><span style="font-weight: 400">Los gráficos de barras son otro de los más populares y utilizados en la visualización de datos.</span></p>
<p style="text-align: center"> </p>
<pre><span style="font-weight: 400;color: #ff00ff">import</span><span style="font-weight: 400"> matplotlib.pyplot </span><span style="font-weight: 400;color: #ff00ff">as</span><span style="font-weight: 400"> plt</span><br /><br /><span style="font-weight: 400">meses = </span><br /><br /><span style="font-weight: 400">ganancias = </span><br /><br /><span style="font-weight: 400">plt.bar(meses,ganancias)</span><br /><br /><span style="font-weight: 400">plt.title(</span><span style="font-weight: 400;color: #800000">'Ganancias en el 2020'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.xlabel(</span><span style="font-weight: 400;color: #800000">'Mes del 2020'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.ylabel(</span><span style="font-weight: 400;color: #800000">'Ganancias (en miles de pesos)'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.show()</span></pre>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img34.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Si necesitas gráficos de barras más avanzados te sugerimos </span><a href="https://pythonspot.com/matplotlib-bar-chart/"><span style="font-weight: 400">este tutorial</span></a><span style="font-weight: 400">, para otros aún más avanzados todavía sugerimos </span><a href="https://www.tutorialspoint.com/matplotlib/matplotlib_bar_plot.htm"><span style="font-weight: 400">este tutorial</span></a><span style="font-weight: 400"> y siempre puedes utilizar alguno de estos </span><a href="https://matplotlib.org/stable/gallery/index.html"><span style="font-weight: 400">ejemplos </span></a><span style="font-weight: 400">(los primeros tres son ejemplos de gráficos de barras).</span></p>
<p style="text-align: center"> </p>
<h3 style="text-align: center"><span style="font-weight: 400;font-size: 14pt">Gráfico circular o de pastel</span></h3>
<p style="text-align: center"><span style="font-weight: 400">El diagrama circular o de pastel es otro que no puede faltar, para eso vamos a recurrir a la función pie (en ingles pie = pastel)</span></p>
<pre><br /><br /><br /><span style="font-weight: 400;color: #ff00ff">import</span><span style="font-weight: 400"> matplotlib.pyplot </span><span style="font-weight: 400;color: #ff00ff">as</span><span style="font-weight: 400"> plt </span><span style="font-weight: 400;color: #99cc00"># Importamos matplotlib</span><br /><br /><span style="font-weight: 400">y = </span><span style="font-weight: 400;color: #99cc00"># Defino las cantidades a representar en el diagrama</span><br /><br /><span style="font-weight: 400">mylabels =  </span><span style="font-weight: 400;color: #99cc00"># Defino que etiqueta va con cada color o seccion</span><br /><br /><span style="font-weight: 400">plt.figure(figsize=(</span><span style="font-weight: 400;color: #008080">10</span><span style="font-weight: 400">,</span><span style="font-weight: 400;color: #008080">10</span><span style="font-weight: 400">)) </span><span style="font-weight: 400;color: #99cc00"># Definimos un buen tamaño</span><br /><br /><span style="font-weight: 400">plt.title(</span><span style="font-weight: 400;color: #800000">'Venta de helados por porcentaje'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.pie(y, labels = mylabels) </span><span style="font-weight: 400;color: #99cc00"># uso la funcion pie para generar el diagrama circular o de pastel (en ingles pie = pastel)</span><br /><br /><span style="font-weight: 400">plt.show() </span><span style="font-weight: 400;color: #99cc00"># Siempre recomendable agregar la funcion show al final</span></pre>
<p style="text-align: center"> </p>
<p style="text-align: center"><span style="font-weight: 400">Este sería el resultado, una gráfica de pastel muy sencilla.</span></p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img37.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Un ejemplo un poco mas avanzado es el siguiente</span></p>
<p style="text-align: center"> </p>
<pre><span style="font-weight: 400">import</span><span style="font-weight: 400"> matplotlib.pyplot </span><span style="font-weight: 400">as</span><span style="font-weight: 400"> plt </span><span style="font-weight: 400;color: #99cc00"># Importamos matplotlib</span><br /><br /><span style="font-weight: 400">y = </span><span style="font-weight: 400;color: #99cc00"># Defino las cantidades a representar en el diagrama</span><br /><br /><span style="font-weight: 400">mylabels =  </span><span style="font-weight: 400;color: #99cc00"># Definimos un array de colores</span><br /><br /><span style="font-weight: 400">mycolors = </span><br /><br /><span style="font-weight: 400">myexplode =  </span><span style="font-weight: 400;color: #99cc00"># Explode nos permite hacer que una seccion del pastel se separe del resto</span><br /><br /><span style="font-weight: 400;color: #99cc00"># myexplode es un array con 4 valores ya que tenemos solo 4 secciones en el pastel</span><br /><br /><span style="font-weight: 400;color: #99cc00"># El primer elemento es mayor a cero mientras que todos los demas son cero, por eso solo el primer elemento se separa del paste.</span><br /><br /><span style="font-weight: 400">plt.figure(figsize=(</span><span style="font-weight: 400;color: #008080">10</span><span style="font-weight: 400">,</span><span style="font-weight: 400;color: #008080">10</span><span style="font-weight: 400">)) </span><span style="font-weight: 400;color: #99cc00"># Definimos un buen tamaño</span><br /><br /><span style="font-weight: 400">plt.title(</span><span style="font-weight: 400;color: #800000">'Venta de helados por porcentaje'</span><span style="font-weight: 400">)</span><br /><br /><span style="font-weight: 400">plt.pie(y, labels = mylabels, startangle = </span><span style="font-weight: 400;color: #008080">120</span><span style="font-weight: 400">, explode = myexplode, colors = mycolors, shadow = </span><span style="font-weight: 400;color: #0000ff">True</span><span style="font-weight: 400">) </span><br /><br /><span style="font-weight: 400;color: #99cc00"># startangle nos permite rotal el pastel, mientras que shadow nos permite agregar una sombra</span><br /><br /><span style="font-weight: 400;color: #99cc00"># colors nos permite definir nuestros propios colores, mientra que explode ya fue explicado</span><br /><br /><span style="font-weight: 400">plt.show() </span></pre>
<p style="text-align: center"> </p>
<p style="text-align: center"><span style="font-weight: 400">Siendo este el resultado</span></p>
<p style="text-align: center"><img style="width: 45%" src="https://aichallenge.utec.edu.uy/wp-content/uploads/2021/03/img40.jpg" /></p>
<p style="text-align: center"><span style="font-weight: 400">Para ver más te recomendamos este </span><a href="https://www.w3schools.com/python/matplotlib_pie_charts.asp"><span style="font-weight: 400">tutorial sencillo</span></a><span style="font-weight: 400">, también </span><a href="https://pythonspot.com/matplotlib-pie-chart/"><span style="font-weight: 400">este tutorial un poco más avanzado</span></a><span style="font-weight: 400"> y como siempre los </span><a href="https://matplotlib.org/stable/gallery/pie_and_polar_charts/pie_features.html"><span style="font-weight: 400">ejemplos del sitio de matplotlib</span></a><span style="font-weight: 400">.</span></p>
<p style="text-align: center"> </p>
<p style="text-align: center"> </p>
<p style="text-align: center"> </p>]]></content:encoded>
                        <category domain="https://aichallenge.utec.edu.uy/community/machine-learning/">Machine Learning</category>                        <dc:creator>taa.admin</dc:creator>
                        <guid isPermaLink="true">https://aichallenge.utec.edu.uy/community/machine-learning/visualizacion-de-datos-simple-con-python-y-matplotlib/#post-121</guid>
                    </item>
                                                </channel>
        </rss>
        