<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Andrea Ridolfi, Author at Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/andrearidolfi/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/author/andrearidolfi/</link>
	<description></description>
	<lastBuildDate>Tue, 01 Nov 2022 07:17:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Andrea Ridolfi, Author at Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/author/andrearidolfi/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Matplotlib Color Palette</title>
		<link>https://blog.finxter.com/how-to-plot-matplotlibs-color-palette-and-choose-your-plot-color/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Thu, 16 Jun 2022 13:37:00 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=24307</guid>

					<description><![CDATA[<p>In this article, we&#8217;ll learn how to generate the Matplotlib color palette and then we will use it to select a specific color for our plot. Problem and Solution Overview Problem: When presenting data, the color that you assign to a plot is very important; a bad color choice can make your data difficult to ... <a title="Matplotlib Color Palette" class="read-more" href="https://blog.finxter.com/how-to-plot-matplotlibs-color-palette-and-choose-your-plot-color/" aria-label="Read more about Matplotlib Color Palette">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-plot-matplotlibs-color-palette-and-choose-your-plot-color/">Matplotlib Color Palette</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article, we&#8217;ll learn how to <strong>generate the <a href="https://blog.finxter.com/matplotlib-full-guide/" data-type="post" data-id="20151" target="_blank" rel="noreferrer noopener">Matplotlib</a> color palette</strong> and then we will use it to select a specific color for our plot. </p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How to Plot Matplotlib&#039;s Color Palette -- and Choose Your Plot Color?" width="937" height="527" src="https://www.youtube.com/embed/bhwarnT22-E?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Problem and Solution Overview</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="1024" height="701" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-128-1024x701.png" alt="" class="wp-image-425598" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-128-1024x701.png 1024w, https://blog.finxter.com/wp-content/uploads/2022/06/image-128-300x205.png 300w, https://blog.finxter.com/wp-content/uploads/2022/06/image-128-768x525.png 768w, https://blog.finxter.com/wp-content/uploads/2022/06/image-128.png 1301w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption><em><strong>Figure 0</strong>: This is the color palette you&#8217;ll learn how to generate in this article!</em></figcaption></figure>
</div>


<p><strong>Problem</strong>: When presenting data, the color that you assign to a plot is very important; a bad color choice can make your data difficult to understand or even less interesting. </p>



<p>However, it is not easy to choose the right colors or the optimal color combinations for the cases in which we have to plot multiple functions at the same time. </p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>Solution</strong>: A solution to this problem is to check the Matplotlib color palette and choose from there, the color that best fits your needs. </p>



<p>We&#8217;ll write a script for generating the Matplotlib color palette inside our script, just before plotting our graphs. </p>



<p>In this way, we will be able to check for the name of the color that is most suited for our needs and assign it to a second plot. </p>



<p>We write the code for generating the color palette as a function; to make it possible to call it every time we need to decide on a particular color to assign to the plots.</p>



<h2 class="wp-block-heading">Code Overview</h2>



<p>We&#8217;ll discuss the following code in this tutorial, in a simple to understand, step-by-step manner:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import numpy as np


def sel_color():

    colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
    
    # sort colors by hue, saturation and value
    by_hsv = []
    for name, color in colors.items():
        t = tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3]))
        by_hsv.append((t, name))
    by_hsv.sort()
    sorted_names = [name for hsv, name in by_hsv]

    n = len(sorted_names)
    ncols = 4
    nrows = n // ncols
    
    # Create the matplotlib window
    fig, ax = plt.subplots()
    
    # Get height and width of the figure
    X, Y = fig.get_dpi() * fig.get_size_inches()
    
    # height of a cell
    h = Y / (nrows + 1)
    
    # width of a cell
    w = X / ncols
    
    # using an index for accessing all the color names
    k = 0
    
    # inserting the colors in the palette by column
    for i in range(ncols):
        for j in range(nrows, 0, -1):
            
            # current row
            row = j * h
            
            # current column
            col = i
            
            # height level for the colors' labels
            y = row
            
            # position of the initial corner of the color box
            xi = w * (col + 0.05)
            
            # position of the final corner of the color box
            xf = w * (col + 0.25)
            
            # initial position of the labels
            xi_text = w * (col + 0.3)

            ax.text(xi_text, y, sorted_names[k], fontsize=(h * 0.8),
                    horizontalalignment='left', verticalalignment='center')

            ax.hlines(y, xi, xf, color=sorted_names[k], linewidth=(h * 0.8))
            k += 1

    ax.set_xlim(0, X)
    ax.set_ylim(0, Y)
    ax.set_axis_off()

    fig.subplots_adjust(left=0, right=1,
                        top=1, bottom=0,
                        hspace=0, wspace=0)
    plt.show()
    selected_c = str(input('Enter the name of the color for your graph: '))
    return selected_c


# x and y array to plot
x = np.linspace(0, 50, 100)
y = x**3 + 3*x - 5

# Plotting
current_c = sel_color()
fig = plt.figure()
ax = fig.subplots()
ax.plot(x, y, color=current_c)
plt.show()
</pre>



<p>If you run this code snippet, you&#8217;ll get the following output:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="638" height="549" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-129.png" alt="" class="wp-image-425611" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-129.png 638w, https://blog.finxter.com/wp-content/uploads/2022/06/image-129-300x258.png 300w" sizes="(max-width: 638px) 100vw, 638px" /></figure>
</div>


<p>You can resize it accordingly to get a more pretty output using Python&#8217;s internal display window tool.</p>



<p>Let&#8217;s dive into the code!</p>



<h2 class="wp-block-heading">Importing Libraries and Packages</h2>



<p>For this example, we just need <code><a title="Best Matplotlib Cheat Sheet" rel="noreferrer noopener" href="https://blog.finxter.com/best-matplotlib-cheat-sheet/" target="_blank">Matpotlib </a></code>and <code><a title="NumPy Tutorial – Everything You Need to Know to Get Started" rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">Numpy</a></code>. </p>



<p>In addition to <code>.pyplot()</code>, which is used for plotting, we also need the module <code>colors</code> that contains functions and <a rel="noreferrer noopener" href="https://blog.finxter.com/an-introduction-to-python-classes-inheritance-encapsulation-and-polymorphism/" data-type="post" data-id="30977" target="_blank">classes</a> for color specification and conversion. We then call it “<code>mcolors</code>”. </p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Link</strong>: You can find the full documentation <a rel="noreferrer noopener" href="https://matplotlib.org/stable/api/colors_api.html" target="_blank">here</a></p>



<p><em>Numpy </em>is used just for <a href="https://blog.finxter.com/how-to-generate-random-integers-in-python/" data-type="post" data-id="32791" target="_blank" rel="noreferrer noopener">generating two random arrays</a> that will be then plotted, after choosing the color that we choose from the generated palette.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import numpy as np
</pre>



<h2 class="wp-block-heading">Generating the Matplotlib Color Palette</h2>



<p>As anticipated in the introduction, the aim of this section is to generate the Matplotlib color palette and display it in a Matplotlib window. </p>



<p>For those who are not familiar with the color palettes that can be used in Python, the following figure shows the Matplotlib color palette that we want to recreate in our script:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="415" height="395" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-111.png" alt="" class="wp-image-24311" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-111.png 415w, https://blog.finxter.com/wp-content/uploads/2021/02/image-111-300x286.png 300w" sizes="auto, (max-width: 415px) 100vw, 415px" /><figcaption><em><strong>Figure 1: </strong>Color palette containing all the names of the colors that can be used within a matplotlib window.</em></figcaption></figure>
</div>


<p></p>



<h2 class="wp-block-heading">Defining the Function and Sorting the Colors by HSV Values</h2>



<p>As anticipated in the introduction, we write this script as a portable function to generate the color palette. Portability means that you can reuse the same function in other scripts just by calling the function name! </p>



<p>We start by calling the function <code>sel_col()</code>.</p>



<p>Within the body of the function, we create a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="post" data-id="5232" target="_blank">dictionary</a> that contains all the names of the colors (the basic ones and the CSS colors) and the <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank">tuple</a> or the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print-hex-without-0x/" data-type="post" data-id="34732" target="_blank">hexadecimal</a> codes that univocally describe a particular color, as <code>key:value</code> pairs; we assign the dictionary to the variable <code>colors</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def sel_color():
  colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
</pre>



<p>As you might see by <a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank">printing</a> the variable <code>colors</code>, the basic colors are defined by a tuple of three values while the other colors are represented by a hexadecimal code. </p>



<p>In order to adopt a uniform nomenclature for the description of each color, we will convert this representation first to an RGBA.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: RGBA is a possible way to describe a color with 4 numbers, the first three correspond to the amount of <strong>R</strong>ed, <strong>G</strong>reen, and <strong>B</strong>lue. The fourth one stands for intensity.</p>



<p>Next, we convert it to an hexadecimal. </p>



<p>The first step can be done by exploiting the function <code>mcolors.to_rgba()</code>, which takes as input the array containing all the tuples representing the different colors.</p>



<p>The second step instead, can be done with the function <code>mcolors.rgb_to_hsv()</code> that takes as input the tuples corresponding to the RGB description of the colors and converts it into HSV format, which stands for <strong>H</strong>ue, <strong>S</strong>aturation, and <strong>V</strong>alue (or Brightness). </p>



<p>We select just the first three values since we do not want to apply any change to the intensity, which moreover, is not provided in the RGB color code.</p>



<p>We store each HSV combination of numbers into a tuple, together with the respective color name and then extend this procedure to all the colors listed in <code>colors</code><em> </em>and hence generate a <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a> of these tuples. </p>



<p>Since <code>colors</code> is a dictionary, to access both its keys and values we write: <code>for name, color in colors.items()</code> in this way the variables <code>name</code> and <code>color</code> refer to the dictionary keys and values, respectively. </p>



<p>To conclude, we sort the list by using the function <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-sort/" data-type="post" data-id="7176" target="_blank">list.sort()</a></code>, passing as input the whole list and we store all of the HSV color tuples into the variable <code>by_hsv</code>. </p>



<p>The following code lines display all the aforementioned procedures.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    # sort colors by hue, saturation and value
    by_hsv = []
    for name, color in colors.items():
        t = tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3]))
        by_hsv.append((t, name))
    by_hsv.sort()</pre>



<p>If we now print the variable <code>by_hsv</code>, we can see that all the colors have been sorted by their HSV values, from the lowest to the highest. </p>



<p>We finish this section by <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-python-list/" data-type="post" data-id="10436" target="_blank">creating a list</a> containing all the names of the colors. To do that, we exploit <a href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank" rel="noreferrer noopener">list comprehension</a> and we store in the list <code>sorted_names</code> just the name of the colors present in the tuples of the <code>by_hsv</code> list.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  sorted_names = [name for hsv, name in by_hsv]</pre>



<h2 class="wp-block-heading">Creating the Color Palette Framework</h2>



<p>At this point, we create the palette that will be displayed in the Matplotlib window. </p>



<p>We start by defining the number of rows and columns. As you can see from the previous figure, we want to have four columns; the number of rows is defined by the ratio between the total number of colors (equal to the <a href="https://blog.finxter.com/python-len/" data-type="post" data-id="22386" target="_blank" rel="noreferrer noopener">length</a> of the list <code>sorted_names</code>) and the number of columns.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  n = len(sorted_names)
  ncols = 4
  nrows = n // ncols
</pre>



<p>At this point we create the Matplotlib window, exploiting the Matplotlib function <code><a href="https://blog.finxter.com/customize-multiple-subplots-in-matplotlib/" data-type="post" data-id="24762" target="_blank" rel="noreferrer noopener">subplots()</a></code><em>.</em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  # Create the matplotlib window
  fig, ax = plt.subplots()</pre>



<p>As you can see from Figure 1, the colors appear in a grid-like framework that uniformly occupies the window. </p>



<p>In order to do that, we have to extract the size of our window and thus define the size that each colored box and its respective label should occupy.</p>



<p>To obtain the height and the width of the figure, we combine together the methods <code>.get_dpi()</code> returning the resolution in dots per inch as a float number and <code>.get_size_inches()</code> returning the size of the figure in inches.</p>



<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f30d.png" alt="🌍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Resources</strong>: Documentation of those two methods can be found <a rel="noreferrer noopener" href="https://www.geeksforgeeks.org/matplotlib-figure-figure-get_dpi-in-python/" data-type="URL" data-id="https://www.geeksforgeeks.org/matplotlib-figure-figure-get_dpi-in-python/" target="_blank">here</a> and <a rel="noreferrer noopener" href="https://www.geeksforgeeks.org/matplotlib-figure-figure-get_size_inches-in-python/" data-type="URL" data-id="https://www.geeksforgeeks.org/matplotlib-figure-figure-get_size_inches-in-python/" target="_blank">here</a>. </p>



<p>By multiplying them together, we hence obtain the size of the figure in dots. </p>



<p>We assign the width and the height values to the variables <code>X</code> and <code>Y</code>. </p>



<p>After that, we calculate the height and width of each row and column (<code>h</code> and <code>w</code>, respectively) by dividing <code>Y</code> and <code>X</code> by the total number of rows and columns (note that for <code>h</code>, we divide <code>Y</code> by <code>nrows +1</code> to obtain a little more space on the upper and lower corners of the window).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  X, Y = fig.get_dpi() * fig.get_size_inches()
  # height of a cell
  h = Y / (nrows + 1)
  # width of a cell
  w = X / ncols
</pre>



<h2 class="wp-block-heading">Inserting the Colored Boxes in the Palette</h2>



<h3 class="wp-block-heading">Position and size of the colored boxes and labels</h3>



<p>Now that we calculated the height and width of the <code>cells</code> of our palette, we can proceed further by inserting in each position the colored boxes and their respective names. </p>



<p>Before accessing the cells in which the figure is “divided” &#8212; actually, the figure is not divided into cells, it is just a way of thinking about that, each cell corresponds to a colored box plus its label &#8212; we define a parameter <code>k</code> for indexing the names of the colors in the <code>sorted_names</code> list.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  # using an index for accessing all the color names
  k = 0
</pre>



<p>At this point, we can access each position of the figure and create all the colored boxes. </p>



<p>In order to do that, we exploit two nested <a rel="noreferrer noopener" href="https://blog.finxter.com/python-loops/" data-type="post" data-id="4596" target="_blank"><code>f</code></a>or loops that will allow us to insert each color in its position. </p>



<p>We start by first filling the first column, then we proceed with the second one, and so on till the fourth one. </p>



<p>The first <code>for</code> loop refers to the columns and will iterate throughout all of them. We specify this by setting the end value <code>ncols</code> equal to four. </p>



<p>On the other hand, the nested <code>for</code> loop is responsible for the rows. Since we want to start creating our boxes from the upper corner, this <code>for</code> loop has to iterate in the reversed order, so the first index will correspond to the last row (specified by the value <code>nrows</code>) and the final index will be 0, which identifies the row at the bottom of the figure. </p>



<p>Within this second <code>for</code> loop, we firstly define two parameters: <code>row</code> and <code>col</code>, which identify the row and the column we are currently working on, respectively. </p>



<p>As you can see, <code>col</code> is equal to the index of the outer <em>for loop </em>while <code>row</code> is defined by multiplying the height of a single cell, <code>h</code>, by the index of the inner <code>for</code> loop (which is iterating through all the rows). </p>



<p>The parameter <code>row</code> will be also responsible for the height level of the colors’ labels.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  # inserting the colors in the palette by column
  for i in range(ncols):
      for j in range(nrows, 0, -1):
          # current row
          row = j * h
          # current column
          col = i
          # height level for the colors' labels
          y = row
</pre>



<p>Now that we can access each position of the figure in the correct order, we start to create the colored boxes. </p>



<p>The first thing to do is to specify the size of the boxes, we do that by defining the initial and final horizontal coordinate of the boxes, we call them “xi” and “xf”, respectively. </p>



<p>As you can see in the code below, “xi” is defined by the cell width, multiplied by the current column position (“col”) to which we also add a small offset (0.05); for “xf”, the procedure is similar, its position has just a different offset, 0.25 instead of 0.05.</p>



<p>From this, you can clearly understand that the width of our boxes will be 0.20. The starting position of the labels, “xi_text” is defined in the same way, just with another offset, this time 0.3.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">         # position of the initial line of the colored square
         xi = w * (col + 0.05)
         # position of the final line of the colored square
         xf = w * (col + 0.25) 
         # initial position of the text
         xi_text = w * (col + 0.3)
</pre>



<p>Once we defined the initial and final position of the edges of the boxes and of the text labels, we can finally create them. </p>



<p>To generate the labels, we exploit the function <em>ax.text()</em>, which generates some axes in which we can insert a text. </p>



<p>We have to specify, as input parameter, the horizontal and vertical position (“xi_text” and “y”, respectively), the label (<code>sorted_names[k]</code>). </p>



<p>We can also specify some other less important and optional parameters, like the font size and the position of the labels with respect to the initial coordinates.</p>



<h2 class="wp-block-heading">Properties of the Colored Boxes and Their Labels</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">       ax.text(xi_text, y, sorted_names[k], fontsize=(h * 0.8),
               horizontalalignment='left', verticalalignment='center')</pre>



<p>To create the boxes, we exploit the function <em>ax.hlines(), </em>which generates an horizontal line.</p>



<p>This time we first specify the vertical coordinate “y”, then the starting and ending point of the line, “xi” and “xf”, respectively; we also specify the color of the line by accessing the name of the colors (using “sorted_names[k]”) and the line width, which corresponds to the height of the box ( ̴ 80% of the cell height). </p>



<p>We end this <em>for loop </em>by incrementing the value of the index “k”; in this way, in the next <a href="https://blog.finxter.com/3-top-design-patterns-in-python-singletons-decorators-and-iterators/" data-type="post" data-id="151218" target="_blank" rel="noreferrer noopener">iteration</a>, we will change <code>row</code> and hence we will be addressing the next color name in the list “<code>sorted_names</code>”.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">       ax.hlines(y, xi, xf,
                 color=sorted_names[k], linewidth=(h * 0.8))
       k += 1</pre>



<p>We are almost done with our function <em>sel_color(), </em>we just conclude by specifying some details regarding the size of the axes in the Matplotlib window and by disabling their visibility.</p>



<p>We also adjust the position of the figure within the <em>Matplotlib</em> window. </p>



<p>In the end, we show the created palette and ask (by using a <em>print</em> statement) to select the name of a color in the palette. The function will return the typed color name, stored in the variable “selected_c”.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  ax.set_xlim(0, X)
  ax.set_ylim(0, Y)
  ax.set_axis_off()

  fig.subplots_adjust(left=0, right=1,
                      top=1, bottom=0,
                      hspace=0, wspace=0)
  plt.show()
  selected_c = str(input('Enter the name of the color for your graph: '))
  return selected_c</pre>



<p>The palette will be shown as represented in Figure 2, which is very similar to the one we had in Figure 1.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="668" height="368" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-113.png" alt="" class="wp-image-24317" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-113.png 668w, https://blog.finxter.com/wp-content/uploads/2021/02/image-113-300x165.png 300w" sizes="auto, (max-width: 668px) 100vw, 668px" /><figcaption><strong><em>Figure 2: </em></strong>Color palette created within the function <em>sel_color()</em> and displaying all the colors available within Matplotlib. As you can see, some colors are repeated but it is just because they can be addressed by typing different names.</figcaption></figure>
</div>


<p></p>



<h2 class="wp-block-heading">Plotting a Graph with the Selected Color</h2>



<p>After having completed the <em>sel_color() </em>function, we create two arrays “x” and “y” and we plot them in another Matplotlib window.</p>



<p>However, before doing that, we call the function <em>sel_color()</em> and assign its returning value (the name of the color that we selected and typed in the terminal, I typed “olivedrab” as an example) to the variable “current_c” which will be inserted as the value of the parameter <em>color, </em>within the <em>ax.plot()</em> function. </p>



<p>The ending result is shown in Figure 3, i.e., a plot that has the color that we chose after checking the just created color palette.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="449" height="320" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-114.png" alt="" class="wp-image-24318" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-114.png 449w, https://blog.finxter.com/wp-content/uploads/2021/02/image-114-300x214.png 300w" sizes="auto, (max-width: 449px) 100vw, 449px" /><figcaption><strong><em>Figure 3: </em></strong>“x” and “y” arrays plotted with the color that we selected from the palette of Figure 2.</figcaption></figure>
</div>


<p></p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>In this article, we defined a function for creating and displaying the Matplotlib color palette.</p>



<p>We first defined the size of the palette, its rows and columns.</p>



<p>Then we calculated the size of each cell and by accessing their position (exploiting two nested <em>for loops</em>) we created the colored boxes and their labels. </p>



<p>Finally, we entered in the terminal the name of the color that we selected and called the function in order to assign that specific color to the plot that we wanted to plot.&nbsp;</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p></p>
<p>The post <a href="https://blog.finxter.com/how-to-plot-matplotlibs-color-palette-and-choose-your-plot-color/">Matplotlib Color Palette</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Matplotlib &#8211; How to Change Subplot Sizes</title>
		<link>https://blog.finxter.com/matplotlib-how-to-change-subplot-sizes/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Tue, 19 Apr 2022 12:53:00 +0000</pubDate>
				<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=25353</guid>

					<description><![CDATA[<p>How to change the size of your matplotlib subplots? The method .subplots() can easily generate multiple subplots within the same plotting figure. But as you may have already noticed, all the subplots have the exact same size and moreover, their size will be adjusted automatically, depending on how many of them you want to display ... <a title="Matplotlib &#8211; How to Change Subplot Sizes" class="read-more" href="https://blog.finxter.com/matplotlib-how-to-change-subplot-sizes/" aria-label="Read more about Matplotlib &#8211; How to Change Subplot Sizes">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/matplotlib-how-to-change-subplot-sizes/">Matplotlib &#8211; How to Change Subplot Sizes</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><strong>How to change the size of your <em><code><a href="https://blog.finxter.com/best-matplotlib-cheat-sheet/" title="Best Matplotlib Cheat Sheet" target="_blank" rel="noreferrer noopener">matplotlib</a></code></em> subplots?</strong></p>



<p>The method<em> <code><a title="Matplotlib Subplots – A Helpful Illustrated Guide" rel="noreferrer noopener" href="https://blog.finxter.com/matplotlib-subplots/" target="_blank">.subplots()</a></code></em> can easily generate multiple subplots within the same plotting figure. But as you may have already noticed, all the subplots have the exact same size and moreover, their size will be adjusted automatically, depending on how many of them you want to display in the same figure. </p>



<h2 class="wp-block-heading">Quick Solution Overview</h2>



<p class="has-global-color-8-background-color has-background">To change the size of subplots in Matplotlib, use the <code>plt.subplots()</code> method with the <code>figsize</code> parameter (e.g., <code>figsize=(8,6)</code>) to specify one size for all subplots &#8212; unit in <a rel="noreferrer noopener" href="https://matplotlib.org/stable/gallery/subplots_axes_and_figures/figure_size_units.html" data-type="URL" data-id="https://matplotlib.org/stable/gallery/subplots_axes_and_figures/figure_size_units.html" target="_blank">inches</a> &#8212; and the <code>gridspec_kw</code> parameter (e.g., <code>gridspec_kw={'width_ratios': [2, 1]}</code>) to specify individual sizes.</p>



<p>Here&#8217;s a quick overview:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Set one size for all subplots
fig, ax = plt.subplots(2, 2, figsize=(8,6))

# Set individual sizes for specific subplots
fig, ax = plt.subplots(1, 2, gridspec_kw={'width_ratios': [2, 1]})</pre>



<p>In the next sections, you&#8217;ll learn how to change the size of each individual subplot. This is useful for tailoring the layout of your graphs and data presentations according to the relevance that you want to assign to each subplot.</p>



<h2 class="wp-block-heading">Simple Example figsize Argument</h2>



<p>In the following example, I&#8217;ll show you how to use the <code>figsize</code> argument of the <code>plt.subplots()</code> method to change the size of a subplot:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3,4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

# define subplots with subplot size
fig, ax = plt.subplots(2, 2, figsize=(8,6))

# define data
x = [0, 1, 2, 3, 4, 5]
y = [i**2 for i in x]

# create subplots
ax[0, 0].plot(x, y, color='black')
ax[0, 1].plot(x, y, color='green')
ax[1, 0].plot(x, y, color='red')
ax[1, 1].plot(x, y, color='blue')

# display the plot
plt.show()
</pre>



<p>Output:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="886" height="678" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-179.png" alt="" class="wp-image-315331" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-179.png 886w, https://blog.finxter.com/wp-content/uploads/2022/04/image-179-300x230.png 300w, https://blog.finxter.com/wp-content/uploads/2022/04/image-179-768x588.png 768w" sizes="auto, (max-width: 886px) 100vw, 886px" /></figure>
</div>


<p>Let&#8217;s change the <code>figsize</code> argument to a smaller <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank" rel="noreferrer noopener">tuple</a> value:</p>



<ul class="wp-block-list"><li>Original subplot: <code>fig, ax = plt.subplots(2, 2, figsize=(8,6))</code></li><li>Changed size: <code>fig, ax = plt.subplots(2, 2, figsize=(3,12))</code></li></ul>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

# define subplots
fig, ax = plt.subplots(2, 2, figsize=(3,12))

# define data
x = [0, 1, 2, 3, 4, 5]
y = [i**2 for i in x]

# create subplots
ax[0, 0].plot(x, y, color='black')
ax[0, 1].plot(x, y, color='green')
ax[1, 0].plot(x, y, color='red')
ax[1, 1].plot(x, y, color='blue')

# display the plot
plt.show()
</pre>



<p>Output &#8212; this strange looking beast:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="360" height="868" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-181.png" alt="" class="wp-image-315345" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-181.png 360w, https://blog.finxter.com/wp-content/uploads/2022/04/image-181-124x300.png 124w" sizes="auto, (max-width: 360px) 100vw, 360px" /></figure>
</div>


<p>This is if you want to change the size of all subplots at once.</p>



<h2 class="wp-block-heading">Simple Solution: Specifying Width Ratios Using subplots() gridspec_kw</h2>



<p>The gridspec_kw parameter of the plt.subplot() function allows you to define a width relationship between individual subplots columns:</p>



<ul class="wp-block-list"><li><code>plt.subplots(2, 2, gridspec_kw={'width_ratios': [2, 1]})</code> sets the first column to double the size of the second column.</li><li><code>plt.subplots(2, 2, gridspec_kw={'width_ratios': [1, 2]})</code> sets the first column to half the size of the second column.</li></ul>



<p>Here&#8217;s an example that draws from the previous code snippet:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

# define subplots
fig, ax = plt.subplots(2, 2, gridspec_kw={'width_ratios': [2, 1]})

# define data
x = [0, 1, 2, 3, 4, 5]
y = [i**2 for i in x]

# create subplots
ax[0, 0].plot(x, y, color='black')
ax[0, 1].plot(x, y, color='green')
ax[1, 0].plot(x, y, color='red')
ax[1, 1].plot(x, y, color='blue')

# display the plot
plt.show()
</pre>



<p>Output:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="732" height="542" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-182.png" alt="" class="wp-image-315363" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-182.png 732w, https://blog.finxter.com/wp-content/uploads/2022/04/image-182-300x222.png 300w" sizes="auto, (max-width: 732px) 100vw, 732px" /></figure>
</div>


<p>You can see how the second column of subplots has only half the size of the first column of subplots as controlled by the <code>gridspec_kw</code> parameter. </p>



<h2 class="wp-block-heading">Advanced Considerations</h2>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Matplotlib – How to Change Subplot Sizes?" width="937" height="527" src="https://www.youtube.com/embed/F4kB2Y72oNs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>The usual <code>.subplots()</code><em> </em>method is really practical for creating multiple subplots but it is not able to access and change the size of these subplots. </p>



<p>On the other hand, the method <code>.add_gridspec()</code> results to be more time-consuming for just creating multiple subplots of the same size but, it constitutes a powerful solution when we want to change the size of individual subplots. </p>



<p>After subdividing the space in a grid-like fashion, you can use the method <code>.add_subplot()</code>, to change the size of each subplot by simply exploiting <a href="https://blog.finxter.com/daily-python-puzzle-list-indexing/" target="_blank" rel="noreferrer noopener" title="List Indexing"><em>Python</em> indexing</a> and <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener" title="Introduction to Slicing in Python">slicing</a>.&nbsp;&nbsp;</p>



<h2 class="wp-block-heading">Slow Guide to Creating the Matplotlib Figure</h2>



<p>In this example, we will only use the <a rel="noreferrer noopener" href="https://blog.finxter.com/matplotlib-full-guide/" data-type="post" data-id="20151" target="_blank">Matplotlib</a> library for plotting the axes and for changing their size; for this reason, we will just import that specific package as shown before:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt</pre>



<p>We start our code by generating the plotting window, i.e. a figure, and then we will add some subplots to it. </p>



<p>If you are already familiar with the creation of multiple subplots, you can skip this section and go directly to the following one. If you instead do not know how to do that, or you simply forgot, it just takes a single code line. </p>



<p>The <em>matplotlib </em>function that is exploited for this aim is called <em><code><a rel="noreferrer noopener" title="https://matplotlib.org/stable/api/figure_api.html" href="https://matplotlib.org/stable/api/figure_api.html" target="_blank">.figure()</a></code></em><a rel="noreferrer noopener" title="https://matplotlib.org/stable/api/figure_api.html" href="https://matplotlib.org/stable/api/figure_api.html" target="_blank">.</a> </p>



<p>This time, we also enter a property called <a rel="noreferrer noopener" title="https://matplotlib.org/stable/tutorials/intermediate/constrainedlayout_guide.html" href="https://matplotlib.org/stable/tutorials/intermediate/constrainedlayout_guide.html" target="_blank"><code>constrained_layout</code> </a>and we set it equal to <em><code>True</code></em>. </p>



<p>This property can be used to fit the plots within the figure cleanly, meaning that they will automatically be nicely distributed in your plotting window, independently of their number. </p>



<p>We finally assign the figure to the variable “<code>fig</code>”.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fig = plt.figure(constrained_layout=True)</pre>



<h2 class="wp-block-heading">.subplots() vs .add_gridspec()</h2>



<p>At this point, we have to create multiple subplots that we will then modify. </p>



<p>One of the most widely used methods for doing that is&nbsp; <code>.subplots()</code>, which generates an array of axes, depending on the numbers that we enter as input parameters. </p>



<p>Suppose we want to create 9 subplots; it is sufficient to type:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Creating the subplots with .subplots() 
ax = fig.subplots(3,3)</pre>



<p>These lines will yield 9 subplots, distributed in a 3&#215;3 grid fashion, like the ones displayed in Figure 1.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="517" height="265" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-55.png" alt="" class="wp-image-25358" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-55.png 517w, https://blog.finxter.com/wp-content/uploads/2021/03/image-55-300x154.png 300w" sizes="auto, (max-width: 517px) 100vw, 517px" /><figcaption><strong><em>Figure 1: </em></strong>By using the method <code>.subplots(3, 3)</code>we are able to generate nine subplots, automatically distributed in a 3&#215;3 grid fashion.&nbsp;&nbsp;</figcaption></figure>
</div>


<p>Achieving the same result using the method<em> <code>.add_gridspec()</code></em> is a lot more tedious and time-consuming. </p>



<p>Indeed, in this latter case, we have to initialize each subplot individually, specifying also the location in which we want it to be created. </p>



<p>More precisely, we have to enter the number of rows and columns of the grid, as input parameters of <code>.add_gridspec()</code><em> </em>and then create each subplot, by using the method <code>add_subplot()</code><em> </em>and specifying for each plot its coordinates on the <code>ax</code><em> </em>grid.</p>



<p>The following code lines describe this procedure.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Creating the subplots with .add_gridspec()
ax = fig.add_gridspec(3, 3)
ax1 = fig.add_subplot(ax[0, 0])
ax1.set_title('[0, 0]')
ax1 = fig.add_subplot(ax[0, 1])
ax1.set_title('[0, 1]')
ax1 = fig.add_subplot(ax[0, 2])
ax1.set_title('[0, 2]')
ax1 = fig.add_subplot(ax[1, 0])
ax1.set_title('[1, 0]')
ax1 = fig.add_subplot(ax[1, 1])
ax1.set_title('[1, 1]')
ax1 = fig.add_subplot(ax[1, 2])
ax1.set_title('[1, 2]')
ax1 = fig.add_subplot(ax[2, 0])
ax1.set_title('[2, 0]')
ax1 = fig.add_subplot(ax[2, 1])
ax1.set_title('[2, 1]')
ax1 = fig.add_subplot(ax[2, 2])
ax1.set_title('[2, 2]')</pre>



<p>We also set a title for each plot, containing the coordinates of its respective location in the grid. The result is then displayed in Figure 2.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="531" height="273" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-56.png" alt="" class="wp-image-25360" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-56.png 531w, https://blog.finxter.com/wp-content/uploads/2021/03/image-56-300x154.png 300w" sizes="auto, (max-width: 531px) 100vw, 531px" /><figcaption><strong><em>Figure 2: </em></strong>The same result displayed in Figure 1 can be obtained using the method <code>add_gridspec(3,3)</code> and creating each plot in each position of the grid by using <code>.add_subplot()</code>. The titles of the plots simply report their coordinates on the grid.</figcaption></figure>
</div>


<p>The huge advantage of using <em><code>.add_gridspec()</code> </em>comes into play when we want to customize the size of each individual subplot. This task cannot be performed by <em><code>.subplots()</code> </em>in any way. </p>



<p>For this reason, if you want to just create some subplots and you are not interested in changing their size, I would recommend using <code>.subplots()</code><em>, </em>because it is more intuitive and faster. </p>



<p>On the other hand, if you are interested in changing the layout of the subplots that are displayed in the figure, go with <code>.add_gridspec()</code><em>. </em></p>



<p>In the next section, we will see how to do that in detail.</p>



<h2 class="wp-block-heading">Changing the Size of Each Subplot with .add_gridspec() and .add_subplot()</h2>



<p>Changing the size of each subplot using <code>.add_gridspec()</code><em> </em>is easier than you may think. </p>



<p>Once we have initialized a 3&#215;3 grid by using <code>.add_gridspec(3, 3)</code><em>, </em>we can adjust the size and hence the number of the subplots simply by varying the input coordinates in the method <code>.add_subplot()</code><em>.</em> </p>



<p>The coordinates of the axis that we enter as input parameters in the .add_subplot() method indicate the initial and final position of the plot (for both rows and columns). It is hence sufficient to know how indexing and slicing work, for tuning the height and the width of each subplot. </p>



<p>As an example, we will now create a plot that is located in the first row and has a width of 2/3 of the entire grid. </p>



<p>Another one that is just one column wide but has a height that spans the entire grid and is placed in the last column. </p>



<p>Lastly, a third plot occupies a 2&#215;2 grid in the remaining space (i.e. last two rows and first two columns). The following code lines describe the procedure for obtaining the aforementioned result.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax = fig.add_gridspec(3, 3)
ax1 = fig.add_subplot(ax[0, 0:2])
ax1.set_title('[0, 0:2]')
ax1 = fig.add_subplot(ax[0:, -1])
ax1.set_title('[0:, -1]')
ax1 = fig.add_subplot(ax[1:, 0:2])
ax1.set_title('[1:, 0:2]')
</pre>



<p>The final result is displayed in Figure 3; the titles above each plot simply show the indexing/slicing that was given as input parameter in order to obtain that specific plot.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="539" height="293" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-57.png" alt="" class="wp-image-25365" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-57.png 539w, https://blog.finxter.com/wp-content/uploads/2021/03/image-57-300x163.png 300w" sizes="auto, (max-width: 539px) 100vw, 539px" /><figcaption><strong><em>Figure 3:</em></strong> Exploiting indexing and <code>.add_subplot()</code><em> </em>allows changing the size of each subplot according to the grid that was previously created through <code>.add_gridspec()</code>.</figcaption></figure>
</div>


<p>As you can see, we customized the size of the subplots by simply changing their initial and final coordinates; the only tricky part remembering how indexing and slicing work in <em>Python.</em></p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>In this example, we saw how to customize the size of individual subplots while keeping all of them plotted in the same figure. </p>



<p>While the method <code>.subplots()</code><em> </em>is faster and easier for creating multiple subplots of the same size, the method <code>.add_gridspec()</code><em> </em>is more tedious and time-consuming. </p>



<p>However, when it comes to changing the size of individual subplots, the first method is useless; on the other hand, it is in these situations that <code>.add_gridspec()</code> shows its power. </p>



<p>By subdividing the figure space in a grid-like fashion, it is possible to change the initial and final coordinates of a plot by just passing them as slicing parameters within the method<code> .add_subplot()</code>. </p>



<p>In this way, it is sufficient to specify the coordinate at which we want a plot to start and the one at which we want it to end. &nbsp;&nbsp;</p>



<h2 class="wp-block-heading">Programmer Humor</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="925" height="507" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-9.png" alt="" class="wp-image-401703" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-9.png 925w, https://blog.finxter.com/wp-content/uploads/2022/06/image-9-300x164.png 300w, https://blog.finxter.com/wp-content/uploads/2022/06/image-9-768x421.png 768w" sizes="auto, (max-width: 925px) 100vw, 925px" /><figcaption><em>&#8220;Real programmers set the universal constants at the start such that the universe evolves to contain the disk with the data they want.&#8221;</em> &#8212; <a rel="noreferrer noopener" href="https://imgs.xkcd.com/comics/real_programmers.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/real_programmers.png" target="_blank">xkcd</a></figcaption></figure>
</div><p>The post <a href="https://blog.finxter.com/matplotlib-how-to-change-subplot-sizes/">Matplotlib &#8211; How to Change Subplot Sizes</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Pandas DataFrame to Python List &#8211; and Vice Versa</title>
		<link>https://blog.finxter.com/dataframe-to-a-list-and-vice-versa/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Thu, 30 Dec 2021 17:19:45 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python List]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=111548</guid>

					<description><![CDATA[<p>In this article, you will learn how to convert a Pandas DataFrame into a list and vice versa. This operation can be useful whenever you just want to focus on a specific column of a DataFrame and you would like to have it as a simple list. Sometimes you might be interested in converting a ... <a title="Pandas DataFrame to Python List &#8211; and Vice Versa" class="read-more" href="https://blog.finxter.com/dataframe-to-a-list-and-vice-versa/" aria-label="Read more about Pandas DataFrame to Python List &#8211; and Vice Versa">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/dataframe-to-a-list-and-vice-versa/">Pandas DataFrame to Python List &#8211; and Vice Versa</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Pandas DataFrame to Python List - and Vice Versa" width="937" height="527" src="https://www.youtube.com/embed/cSO0cR0XCF0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>In this article, you will learn how to convert a <em><a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank" rel="noreferrer noopener">Pandas</a></em> DataFrame into a list and vice versa. </p>



<p>This operation can be useful whenever you just want to focus on a specific column of a DataFrame and you would like to have it as a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank">simple list</a>. Sometimes you might be interested in converting a list into a <em>Pandas</em> DataFrame, in order to exploit the numerous functions dedicated to DataFrames and easily access/edit their content. </p>



<h2 class="wp-block-heading">Long story short</h2>



<p>Converting a DataFrame into a list represents a relatively easy and quick procedure. </p>



<ul class="wp-block-list"><li>Exploiting <em>Pandas</em> in order to correctly access specific columns or DataFrame subsets we are interested in, it is then sufficient to use the function <code>.values.tolist()</code> in order to convert the selected elements into a list. </li><li>The opposite function, which allows converting a list into a DataFrame is the <em>Pandas</em> function <code>.DataFrame()</code><em>.</em></li></ul>



<p></p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong><em>Syntax</em></strong></td><td><code>.tolist()</code></td><td></td></tr><tr><td><strong><em>Details</em></strong></td><td>When applied to a DataFrame, use first the method <code>.values()</code> to obtain the elements of that specific DataFrame and then apply <code>.tolist()</code> </td><td>&nbsp;</td></tr><tr><td><strong><em>Return Value</em></strong></td><td>A list containing the values of the selected DataFrame or DataFrame portion</td></tr></tbody></table></figure>



<p>In the remaining article, we&#8217;ll go over this code snippet of different methods to convert a DataFrame to a list and back:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd


url = "my_table.csv"
doc = pd.read_csv(url, sep=',')
df = pd.DataFrame(doc)

# convert a column of the DF into a list
new_list = df[('State')].values.tolist()

# convert multiple columns of the DF into a list
new_list = df.loc[:, ('Year', 'State')].values.tolist()

# convert a row of DF into a list
new_list = df.loc[3].values.tolist()

# convert a list into a DF
new_df = pd.DataFrame(new_list)
</pre>



<p>This is how the first couple of lines of the sample data looks like:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="742" height="471" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-61.png" alt="" class="wp-image-111593" srcset="https://blog.finxter.com/wp-content/uploads/2021/12/image-61.png 742w, https://blog.finxter.com/wp-content/uploads/2021/12/image-61-300x190.png 300w" sizes="auto, (max-width: 742px) 100vw, 742px" /></figure></div>



<h2 class="wp-block-heading">Import and Read Data as a Pandas DataFrame</h2>



<p>We start our script by <a href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="post" data-id="35926" target="_blank" rel="noreferrer noopener">importing <em>Pandas</em></a><em>, </em>which allows using DataFrames and performing numerous operations with them. </p>



<p>After that, we read a set of data from a <code>.csv</code> file using the <em>Pandas </em>function <code><a rel="noreferrer noopener" href="https://blog.finxter.com/read-and-write-flat-files-with-pandas/" data-type="post" data-id="62847" target="_blank">.read_csv()</a></code>, which accepts as only mandatory input parameter the path of the <code>.csv</code> file. </p>



<p>We also specify the type of separator that is used in the file by adding the optional parameter <code>sep = ","</code>. </p>



<p>After this step, we use the <em>Pandas</em> function <code>.DataFrame()</code> to convert the content of the <code>.csv</code> file into a <em>Pandas</em> DataFrame and we assign it to the variable <code>df</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd

url = r"path of the .csv file"
doc = pd.read_csv(url, sep=',')
df = pd.DataFrame(doc)</pre>



<h2 class="wp-block-heading">What’s a DataFrame?</h2>



<p>DataFrames describe <strong>heterogeneous table-like data structures</strong>, consisting of multiple rows and columns, each of which is labeled. </p>



<p>The rows and columns hence identify a table, whose cells can be used to store data. </p>



<p>Compared to lists and arrays, DataFrames are more versatile structures when it comes to modifying the content of their cells (actually the data stored in each cell). Indeed, it is possible to point to specific columns/rows by just referring to their label. For a detailed description of DataFrames, please refer to <a rel="noreferrer noopener" href="https://www.tutorialspoint.com/python_pandas/python_pandas_dataframe.htm" data-type="URL" data-id="https://www.tutorialspoint.com/python_pandas/python_pandas_dataframe.htm" target="_blank">this</a> and <a rel="noreferrer noopener" href="https://www.geeksforgeeks.org/python-pandas-dataframe/" data-type="URL" data-id="https://www.geeksforgeeks.org/python-pandas-dataframe/" target="_blank">this</a> tutorial.</p>



<p>The imported <code>.csv</code> file contains information regarding the tobacco consumption in different states and is subdivided into seven different columns which contain data on the state, year etc.</p>



<p>In particular, the first column refers to the year and the second one to the State in which the data have been collected. It is possible to find out all the headings of a certain DataFrame by exploiting the <em>Pandas</em> function <code>.columns()</code> which gives as output all the names of the headers featured in the DataFrame. In order to display all the headers of our <code>.csv</code> file, we call this function in our script and we <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">print</a> its value.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(df.columns)</pre>



<p>The result of this command will be:</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.finxter.com/wp-content/uploads/2021/12/image-60.png" alt="" class="wp-image-111565" width="482" height="50" srcset="https://blog.finxter.com/wp-content/uploads/2021/12/image-60.png 643w, https://blog.finxter.com/wp-content/uploads/2021/12/image-60-300x31.png 300w" sizes="auto, (max-width: 482px) 100vw, 482px" /></figure></div>



<p>You can clearly see that our DataFrame presents seven columns, each of which contains specific information.</p>



<h2 class="wp-block-heading">Converting a Single Column of the DataFrame into a List</h2>



<p>Let’s now suppose we are interested in creating a list containing all those elements that are stored under the header ‘<code>State</code>’; in order to do that, we proceed as follow:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># convert a column of the data frame into a list
new_list = df[('State')].values.tolist()</pre>



<p>As you can see from the script, we used the combination of two different functions for achieving the objective: <code>.values()</code> and <code>.tolist()</code>. </p>



<p>The first one is used to convert the column presenting “<code>State</code>” as header of the DataFrame into a <a href="https://blog.finxter.com/numpy-tutorial/" data-type="post" data-id="1356" target="_blank" rel="noreferrer noopener">Numpy array</a>, consisting of a single column and <code>n</code><em> </em>rows; the function <code>.tolist()</code> is then used to convert the array into a list. </p>



<p>The procedure can be used irrespectively of the type of data contained within the DataFrame; whether you have strings or floats, the final result is the same.</p>



<h2 class="wp-block-heading">Converting Multiple Columns of the DataFrame into a List</h2>



<p>It is also possible to create <a href="https://blog.finxter.com/python-list-of-lists/" data-type="post" data-id="7890" target="_blank" rel="noreferrer noopener">multidimensional lists</a> by converting multiple columns of our initial DataFrame. </p>



<p>This can be easily achieved by <a href="https://blog.finxter.com/daily-python-puzzle-list-indexing/" data-type="post" data-id="84" target="_blank" rel="noreferrer noopener">indexing</a> in the correct way the subset of data we are interested in. </p>



<p>Suppose now we are interested in converting into a list the data contained in the columns “<code>Year</code>” and “<code>State</code>”. </p>



<p>We can employ the <em>Pandas</em> function <code>.loc[]</code> in order to access a subset of the DataFrame; after that, we use the same procedure as before, i.e., <code>.values.tolist()</code>. </p>



<p>The result will be a list containing other <code>n</code><em> </em>lists, whose elements are the n-th “<code>Year</code>” and “<code>State</code>”. </p>



<p>The following lines display the procedure.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># convert more columns of the data frame into a list
new_list = df.loc[:, ('Year', 'State')].values.tolist()</pre>



<p>As you can see, in order to index all the elements of the columns “<code>Year</code>” and “<code>State</code>”, we used the following nomenclature: <code>.loc[:, (‘Year’, ‘State’)]</code>, which means that from our DataFrame we want to index all the rows (using the colon) and the columns identified by the headers “<code>Year</code>” and “<code>State</code>”. </p>



<p>If you are interested in more details about the <code>DataFrame.loc[]</code> function, please refer to <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" data-type="URL" data-id="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html" target="_blank" rel="noreferrer noopener">the docs</a>.</p>



<h2 class="wp-block-heading">Converting a DataFrame Row into a List</h2>



<p>So far we have seen how to convert single and/or multiple columns of a DataFrame into a list; however, you might be wondering whether it is possible to do the same with the rows of a DataFrame. </p>



<p>The answer is of course <strong>yes</strong>, and it turns out to be quite simple! </p>



<p>If you remember the previous paragraph, when we used the function <code>.loc[ ]</code>, we indexed all the rows and the two columns of interest. If we are now interested in just a single specific row of the DataFrame, it will be sufficient to just specify the number of the row we want to convert and then use again the function <code>values.tolist()</code>. The following code lines describe the procedure:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># convert a line of the data frame into a list
new_list = df.loc[3].values.tolist()</pre>



<p>The result will be a list containing all the elements of the fourth (just in this case, since we typed the number 3) row; each element of the list will correspond to a single element of the row.</p>



<h2 class="wp-block-heading">Convert a List into a DataFrame</h2>



<p>Let’s suppose we are now interested in the opposite task, i.e., converting a list into a DataFrame.</p>



<p>Also in this case, the solution to the problem is very simple; it will be sufficient to use the <em>Pandas</em> function <code>.DataFrame()</code><em> </em>with the list as input parameter. </p>



<p>In order to illustrate the procedure, let’s convert the list obtained from the previous parts back into a DataFrame called “<code>new_df</code>”.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># convert list into data frame
new_df = pd.DataFrame(new_list)</pre>



<p>Keep in mind that this new DataFrame will not have the headers of the original one since we obtained it just from the elements of an independent list.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In this article, we saw different options to convert entire or parts of DataFrames into lists and vice versa. </p>



<p>Depending on what you are doing with your script, a DataFrame or a list can represent a more versatile structure to work with. As you saw, the conversion is extremely easy and takes just a couple of code lines.  </p>



<p>The post <a href="https://blog.finxter.com/dataframe-to-a-list-and-vice-versa/">Pandas DataFrame to Python List &#8211; and Vice Versa</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Smoothing Your Data with the Savitzky-Golay Filter and Python</title>
		<link>https://blog.finxter.com/smoothing-your-data-with-the-savitzky-golay-filter-and-python/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Wed, 26 May 2021 16:47:38 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Data Visualization]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=30404</guid>

					<description><![CDATA[<p>This article deals with signal processing. More precisely, it shows how to smooth a data set that presents some fluctuations, in order to obtain a resulting signal that is more understandable and easier to be analyzed. In order to smooth a data set, we need to use a filter, i.e. a mathematical procedure that allows ... <a title="Smoothing Your Data with the Savitzky-Golay Filter and Python" class="read-more" href="https://blog.finxter.com/smoothing-your-data-with-the-savitzky-golay-filter-and-python/" aria-label="Read more about Smoothing Your Data with the Savitzky-Golay Filter and Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/smoothing-your-data-with-the-savitzky-golay-filter-and-python/">Smoothing Your Data with the Savitzky-Golay Filter and Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This article deals with signal processing. More precisely, it shows how to smooth a data set that presents some fluctuations, in order to obtain a resulting signal that is more understandable and easier to be analyzed. In order to smooth a data set, we need to use a filter, i.e. a mathematical procedure that allows getting rid of the fluctuations generated by the intrinsic noise present in our data set. <em>Python</em> provides multiple filters, they differentiate based on the mathematical procedure with which they process the data.</p>



<p>In this article, we will see one of the most widely used filters, the so-called <strong>Savitzky-Golay filter</strong>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Smoothing Your Data with the Savitzky-Golay Filter and Python" width="937" height="527" src="https://www.youtube.com/embed/I_K7cVlg2Cc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>To illustrate its functioning and its main parameters, we herein apply a Savitzky-Golay filter to a data set and see how the generated fitting function changes when we change some of the parameters.</p>



<h2 class="wp-block-heading">Long Story Short</h2>



<p>The Savitzky-Golay filter is a low pass filter that allows smoothing data. To use it, you should give as input parameter of the function the original noisy signal (as a one-dimensional array), set the window size, i.e. n° of points used to calculate the fit, and the order of the polynomial function used to fit the signal.</p>



<p>Table 1 sums up the mandatory parameters that you need to choose in order to make your Savitzky-Golay filter working properly.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><strong><em>Syntax:</em></strong></td><td><em><code>savgol_filter()</code></em></td><td></td></tr><tr><td><strong><em>Parameters:</em></strong></td><td><code>x</code><em> (array-like)</em></td><td><em>data to be filtered</em></td></tr><tr><td></td><td><em>window <code>length</code> (int)</em></td><td><em>length of the filter window (odd number)</em></td></tr><tr><td></td><td><em><code>polyorder</code> (int)</em></td><td><em>order of the polynomial function used to fit</em></td></tr><tr><td><strong><em>Return Value</em></strong></td><td><em><code>y</code> (ndarray)</em></td><td><em>the filtered data</em></td></tr></tbody></table><figcaption><strong><em>Table 1</em></strong></figcaption></figure>



<p>These are just the mandatory parameters that you need to know in order to make the function work; for further details, have a look at the <a href="https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.signal.savgol_filter.html" target="_blank" rel="noreferrer noopener" title="https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.signal.savgol_filter.html">official documentation</a>.</p>



<h2 class="wp-block-heading">How Does the Savitzky-Golay Filter Work?</h2>



<p>We might be interested in using a filter, when we want to smooth our data points; that is to approximate the original function, only keeping the important features and getting rid of the meaningless fluctuations. In order to do this, successive subsets of points are fitted with a polynomial function that minimizes the fitting error. </p>



<p>The procedure is iterated throughout all the data points, obtaining a new series of data points fitting the original signal. If you are interested in knowing the details of the Savitzky-Golay filter, you can find a comprehensive description <a href="https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter" target="_blank" rel="noreferrer noopener" title="https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter">here</a>.</p>



<h2 class="wp-block-heading">Smoothing a data set using a Savitzky-Golay filter</h2>



<h3 class="wp-block-heading">Generating a noisy data set</h3>



<p>As explained above, we use a filter whenever we are interested in removing noise and/or fluctuations from a signal. We hence start our example by generating a data set of points that contains a certain amount of noise. To do that, we use <em><a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener" title="NumPy Tutorial – Everything You Need to Know to Get Started">Numpy </a></em>and exploit the function <code><a href="https://blog.finxter.com/python-random-module/" title="Python’s Random Module – Everything You Need to Know to Get Started" target="_blank" rel="noreferrer noopener">.random()</a></code><em> </em>(see the <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.random.html" target="_blank" rel="noreferrer noopener" title="https://numpy.org/doc/stable/reference/random/generated/numpy.random.random.html">documentation</a>)<em>.</em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np

# Generating the noisy signal 
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x) + np.cos(x) + np.random.random(100)
</pre>



<h3 class="wp-block-heading">Applying the Savitzky-Golay Filter</h3>



<p>In order to apply the Savitzky-Golay filter to our signal, we employ the function <code>savgol_filter()</code>, from the <code>scipy.signal</code> package. This function takes as first input the array containing the signal that we want to filter, the size of the “window” that is used on each iteration for smoothing the signal, and the order of the polynomial function employed for fitting the original dataset. </p>



<p>As we will see, the larger the window the less accurate the fitting and the smoothing procedures because we will force the function to average a greater portion of the signal. In the following code lines, we import the <code>savgol_filter()</code> function and apply it to the previously defined “y” array.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from scipy.signal import savgol_filter
# Savitzky-Golay filter
y_filtered = savgol_filter(y, 99, 3)
</pre>



<p>In this first example, we start with a window size of 99, which means that the function will take 99 points (almost all the points) of the initial signal to compute an average; for this reason, we do not expect to obtain good results; please also note that the order of the polynomial functions used in the fitting procedure is three.</p>



<p>We can now use <em><a href="https://blog.finxter.com/matplotlib-full-guide/" title="Matplotlib — A Simple Guide with Videos" target="_blank" rel="noreferrer noopener">Matplotlib </a></em>to plot both the original signal and the one filtered with the Savitzky-Golay filter. If you want to become a Matplotlib expert and data visualization wizard, check out our<a href="https://academy.finxter.com/university/matplotlib-a-guide-to-becoming-a-data-visualization-wizard/" target="_blank" rel="noreferrer noopener" title="https://academy.finxter.com/university/matplotlib-a-guide-to-becoming-a-data-visualization-wizard/"> course on the Finxter Computer Science Academy</a>. It&#8217;s free for all premium members!</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

# Plotting
fig = plt.figure()
ax = fig.subplots()
p = ax.plot(x, y, '-*')
p, = ax.plot(x, y_filtered, 'g')
plt.subplots_adjust(bottom=0.25)
</pre>



<p>The final result is displayed in Figure 1.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="450" height="285" src="https://blog.finxter.com/wp-content/uploads/2021/05/image-39.png" alt="" class="wp-image-30407" srcset="https://blog.finxter.com/wp-content/uploads/2021/05/image-39.png 450w, https://blog.finxter.com/wp-content/uploads/2021/05/image-39-300x190.png 300w" sizes="auto, (max-width: 450px) 100vw, 450px" /><figcaption><strong><em>Figure 1: </em></strong>Plot displaying the original noisy signal (blue line) and the one filtered using a Savitzky-Golay filter with a sampling window size of 99 points and 3<sup>rd</sup> order polynomial functions (green curve).</figcaption></figure></div>



<h3 class="wp-block-heading">Varying the sampling window size and the order of the polynomial function</h3>



<p>In the previous section we set the size of the sampling window to 99, which means that the filter takes as input 99 points “at a time” to compute the fitting function. Since the total number of points in the original signal is 100, the result is not really accurate (as you can also see in Figure 1). We will now create a Slider button, with which we will be able to change the size of the sampling window and see its effects immediately in the plotted graph, in order to get a better understanding of the filter working principle.</p>



<p>To introduce a Slider button in the plot, we exploit the <a href="https://blog.finxter.com/matplotlib-widgets-button/" target="_blank" rel="noreferrer noopener" title="Matplotlib Widgets — How to Make Your Plot Interactive With Buttons">Matplotlib.widget</a><em> </em>library and start by defining the properties of the button like its size and position on the matplotlib window and also the numerical values accessible through it.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Defining the Slider button
ax_slide = plt.axes([0.25, 0.1, 0.65, 0.03]) #xposition, yposition, width and height

# Properties of the slider
win_size = Slider(ax_slide, 'Window size', valmin=5, valmax=99, valinit=99, valstep=2)</pre>



<p>At this point, we have to define a function that will update the plot with the current value indicated by the Slider. We call the function “update”, it will get the current slider value (“win_size.val”), filter the original signal again with the new window size and plot the new filtered signal in the graph. The following code lines describe the procedure.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Updating the plot
def update(val):
    current_v = int(win_size.val)
    new_y = savgol_filter(y, current_v, 3)
    p.set_ydata(new_y)
    fig.canvas.draw() #redraw the figure
</pre>



<p>If you are looking for a more detailed description about how to incorporate sliders and other widgets in <em>Python, </em>have a look at this video:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Matplotlib Widgets -- Creating Interactive Plots with Sliders" width="937" height="527" src="https://www.youtube.com/embed/Hn24Q9MPAsk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>If we now plot the resulting figure, we would get the output displayed in Figure 2.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="427" height="290" src="https://blog.finxter.com/wp-content/uploads/2021/05/image-40.png" alt="" class="wp-image-30409" srcset="https://blog.finxter.com/wp-content/uploads/2021/05/image-40.png 427w, https://blog.finxter.com/wp-content/uploads/2021/05/image-40-300x204.png 300w" sizes="auto, (max-width: 427px) 100vw, 427px" /><figcaption><strong><em>Figure 2:</em></strong> Original signal (blue curve), filtered signal using a window size of 99 points (green curve) and the slider button that allows changing the size of the sampling window.</figcaption></figure></div>



<p>The last thing to do now, is to specify when the function “update” is triggered; we want it to be activated every time the value of the slider button gets changed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># calling the function "update" when the value of the slider is changed
win_size.on_changed(update)
plt.show()</pre>



<p>If we now try to reduce the size of the sampling window, we will appreciate a visible improvement in the fitting signal; this is because the Savitzky-Golay filter is called multiple times for fitting a lower amount of points at a time, hence improving the result of the fitting function. Figure 3 shows the result obtained by setting the size of the sampling window at 5 points.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="420" height="287" src="https://blog.finxter.com/wp-content/uploads/2021/05/image-41.png" alt="" class="wp-image-30411" srcset="https://blog.finxter.com/wp-content/uploads/2021/05/image-41.png 420w, https://blog.finxter.com/wp-content/uploads/2021/05/image-41-300x205.png 300w" sizes="auto, (max-width: 420px) 100vw, 420px" /><figcaption><strong>Figure 3:</strong> Original noisy signal (blue curve), fitted with a Savitzky-Golay filter, using 3<sup>rd</sup> order polynomial functions and a 5-points size sampling window.</figcaption></figure></div>



<p>As can be seen in Figure 3, by reducing the size of the sampling window, the filtering step allows to better follow the fluctuations of the signal; in this way, the resulting signal will appear less smoothed and more detailed.</p>



<h3 class="wp-block-heading">General guidelines for filtering your data</h3>



<p>As you saw in the article, by tuning the size of the sampling window, the result of the filtering step changes quite drastically. In common practice, you should always try to keep the order of the <a href="https://blog.finxter.com/np-polyfit/" target="_blank" rel="noreferrer noopener" title="np.polyfit() — Curve Fitting with NumPy Polyfit">polynomial fitting</a> functions as low as possible in order to introduce as little distortion of the original signal as possible. Regarding the size of the sampling window, you should adjust its value in order to obtain a filtered signal which preserves all the meaningful information contained in the original one but with less noise and/or fluctuations as possible.</p>



<p>Keep in mind that in order to have your Savitzky-Golay filter working properly, you should always choose an odd number for the window size and the order of the polynomial function should always be a number lower than the window size.</p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>In this article, we learned about the Savitzky-Golay filter, which is one of the most widely used signal filter in <em>Python. </em>We started by plotting a noisy signal and we then introduced the Savitzky-Golay filter with which we were able to get rid of the noise. By employing a slider button, we were also able to appreciate the variations in the fitting function as a consequence of the reduction of the sampling window size.   </p>
<p>The post <a href="https://blog.finxter.com/smoothing-your-data-with-the-savitzky-golay-filter-and-python/">Smoothing Your Data with the Savitzky-Golay Filter and Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Manipulating Dates and Times in Python</title>
		<link>https://blog.finxter.com/manipulating-dates-and-times-in-python/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Mon, 19 Apr 2021 11:09:57 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Time]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=28349</guid>

					<description><![CDATA[<p>In this article we will cover some basic features of the datetime module in Python. More specifically, we will see how to extract the current date and time and how to implement these features within a script in order to realize time-driven actions. Long Story Short The datetime module in Python allows you to deal ... <a title="Manipulating Dates and Times in Python" class="read-more" href="https://blog.finxter.com/manipulating-dates-and-times-in-python/" aria-label="Read more about Manipulating Dates and Times in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/manipulating-dates-and-times-in-python/">Manipulating Dates and Times in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this article we will cover some basic features of the <em><a href="https://blog.finxter.com/how-to-work-with-dates-and-times-in-python/" target="_blank" rel="noreferrer noopener" title="NumPy Datetime: How to Work with Dates and Times in Python?">datetime </a></em>module in <em>Python. </em>More specifically, we will see how to extract the current date and time and how to implement these features within a script in order to realize time-driven actions.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Date and Time - A Simple Overview" width="937" height="527" src="https://www.youtube.com/embed/CcpZRdXVQPk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Long Story Short</h2>



<p>The <code>datetime</code> module in <em>Python</em> allows you to deal with date and time expressions. By exploiting classes like <code>.time()</code> and/or <em><code>.datetime()</code></em> you can express times and dates in a dedicated format. </p>



<p>The class <em><code><strong>.timedelta()</strong></code> </em>allows you to define a specific time duration interval and add it to a <code>datetime</code> expression. </p>



<p>The method <em><code><strong>.today()</strong></code> </em>can be then used to extract the current time or/and datetime. You can then convert a specific time interval expressed with the <code>.timedelta()</code><em> </em>class into seconds y exploiting the method <code>.total_seconds()</code><em>. </em></p>



<p>Finally, if you want to extract the microseconds amount from a time expression, you can easily achieve the result by using the method <em><code>.microsecond()</code>.</em></p>



<h2 class="wp-block-heading">The datetime Module</h2>



<p>The <code>datetime</code><em> </em>module contains multiple classes, the most famous and used are:</p>



<ul class="wp-block-list"><li><em><code><strong>.time</strong></code> </em>&#8211; it gives as output an idealized time in the format hours : minutes : seconds</li><li><code><strong>.datetime</strong></code> &#8211; gives as output a combination of a date and a time in the format <code>year - month - day hour : minutes : seconds</code></li><li><code><strong>.timedelta</strong></code><em> </em>&#8211; expresses a duration, indicated as the difference between two dates, times or datetimes.</li></ul>



<p>The following code lines provide an example of these three classes.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import datetime

# express a time
print(datetime.time(10, 23, 45))
# 10:23:45

# express a date and time
print(datetime.datetime(2019, 2, 3, 10, 23, 45))
# 2019-02-03 10:23:45

# add to a date and time a specific duration
time1 = datetime.datetime(2019, 2, 3, 10, 23, 45)
delta = datetime.timedelta(days=4, hours=3)
time2 = time1 + delta
print(time2)
# 2019-02-07 13:23:45</pre>



<p>As you can see in the example, it is possible to express times and dates in a dedicated format by exploiting the module <em>datetime </em>and its two classes <em>time </em>and <em>datetime, </em>respectively. </p>



<p>We then defined a specific date and time and assigned their values to the variable “time1”. We then define a time duration (i.e. 4 days and 3 hours) and assign it to the variable “delta”; finally, we obtain the expression for the date and time corresponding to “time1” after an amount of time equal to “delta” has passed. </p>



<p>Please note when defining the .timedelta(), we used the arguments days and hours; in a similar way, we could have also specified other intervals by using all the available arguments for this function (see the <a href="https://docs.python.org/3/library/datetime.html" target="_blank" rel="noreferrer noopener" title="https://docs.python.org/3/library/datetime.html">official documentation</a>).</p>



<h2 class="wp-block-heading">Get the Current Date and Time with .today()</h2>



<p>In the case we want to get the current time and/or the current date, we can exploit the method <code><strong>.today()</strong></code><em>; </em>it can be applied to both the <em>date</em> and <em>datetime</em> classes and it will return the current date and the current date and time (at the microsecond precision), respectively. The following code lines show an example of how it works.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#get current date
current_date = datetime.date.today()
print(current_date)
# 2021-04-10

#get current date and time
current_dt = datetime.datetime.today()
print(current_dt)
# 2021-04-10 15:17:12.641393</pre>



<h2 class="wp-block-heading">Express a Duration in Seconds with .total_seconds()</h2>



<p>In some applications it might be useful to express a specific amount of time in seconds, without using the <code><strong>hours : minutes : seconds</strong></code> notation. </p>



<p>Let’s take, for example the duration that we applied in the previous section: it was 4 days and 3 hours in total. If we want to obtain the respective number of seconds that corresponds to this period of time, we will just have to type:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Get the duration in seconds
print(delta.total_seconds())
# 356400.0</pre>



<p>You can also verify that 356400.0 is the correct answer by making the conversion manually, which would be: 4(days) * 24(hours) * 60(minutes) * 60(seconds) + 3(hours) * 60(minutes) * 60(seconds) = 356400.<strong><em></em></strong></p>



<h2 class="wp-block-heading">Extract the Microseconds Value from the Time Notation with the .microsecond Attribute</h2>



<p>Sometimes we might be interested in obtaining the number of microseconds that have passed from a specific instant of time. In this case, we would have to extract from the whole time expression, just the part that is indicating the microseconds. In order to do that, we can use the attribute <code>.microsecond</code><em>, </em>which gives as output an integer number, corresponding to the microseconds elapsed in the indicated time.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># extract the microseconds from the current time
current_microsec = datetime.datetime.today().microsecond
print(current_microsec)
# 641393</pre>



<p>Please note that the method <code>.microsecond</code><em> </em>just extracts the corresponding microseconds number from a specific time definition; it does not convert a time duration into microseconds.</p>



<p>Now that we have familiarized with some of the functions for handling the date and time in <em>Python</em>, we will see through a practical example, how to exploit the above explained features to perform time-controlled operations within a <em>Python</em> script.</p>



<h2 class="wp-block-heading">Put Your Script Asleep and Wake It Up Every Three Seconds</h2>



<p>In this example we will see how to handle the time within a script and how to use the above-mentioned functions to put the script asleep for some seconds. This is a crucial thing in lots of applications where “heavy” tasks have to be performed or in cases where your script has to run for long periods of time and you do not want your system to be active for the whole script duration.</p>



<p>We start by obtaining the current date and time using the method<em> </em><code>.datetime.today()</code><em>, </em>then we define a time interval of three seconds by exploiting the method <code>.timedelta()</code>. After this, we define a future date and time instant, called “future”, which is obtained by summing the three seconds time interval to the initial time.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># make the script sleeping for some time
t = datetime.datetime.today()
delta = datetime.timedelta(seconds=3)
future = t + delta</pre>



<p>Now we need to create a <em>for <a href="https://blog.finxter.com/python-loops/" title="Python Loops" target="_blank" rel="noreferrer noopener">loop</a>,</em> in order to perform multiple iterations (in this example we will iterate three times) in which we will “put the script asleep and wake it up” alternately. </p>



<p>We define the duration of the sleeping time by converting the 3 seconds time interval into seconds; it may sounds dumb (and in this case it is) but if we were to choose a longer time interval, like days, we would have had to obtain the interval duration expressed in seconds, and also, we need it to be an integer number, not expressed in time notation. </p>



<p>To put the script asleep, we exploit the method <code>.sleep()</code><em>, </em>from the <code>time</code><em> </em>module. This method accepts as input an integer, corresponding to the number of seconds we want our system to be asleep. When the 3 seconds have passed, we print the current time with a sentence saying that 3 seconds have actually passed from the previous iteration.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import time

for i in range(3):
    # sleep for the time difference between the initial time and the future (in sec)
    time.sleep(delta.total_seconds())
    print("It's " + str(datetime.datetime.today()) + " 3 sec have passed")

'''
   It's 2021-04-11 11:42:33.767437 3 sec have passed
   It's 2021-04-11 11:42:36.777588 3 sec have passed
   It's 2021-04-11 11:42:39.787928 3 sec have passed
'''</pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p>In this article we learnt how to deal with time and date notations in <em>Python </em>and how to use these features within a script. We explored different modules and methods for obtaining the current time, date and also for calculating time intervals (and more!). In the end, we exploited these functions to write a short script which allowed putting asleep the system for a specific amount of time and waking it up at precise time intervals. This example can be extremely useful when designing scripts that have to run for long periods and we do not want to keep the system active for all that time.</p>
<p>The post <a href="https://blog.finxter.com/manipulating-dates-and-times-in-python/">Manipulating Dates and Times in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Display, Modify and Save Images in Matplotlib</title>
		<link>https://blog.finxter.com/display-modify-and-save-images-with-matplotlib/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Mon, 29 Mar 2021 10:54:55 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=27129</guid>

					<description><![CDATA[<p>This article will show you how to visualize, modify and save images in Python, more specifically in Matplotlib. In the following sections, we will see how to load images, how to modify some of their properties and finally how to save them. Long story short If you want to import an image and to display ... <a title="How to Display, Modify and Save Images in Matplotlib" class="read-more" href="https://blog.finxter.com/display-modify-and-save-images-with-matplotlib/" aria-label="Read more about How to Display, Modify and Save Images in Matplotlib">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/display-modify-and-save-images-with-matplotlib/">How to Display, Modify and Save Images in Matplotlib</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Display, Modify and Save Images in Matplotlib" width="937" height="527" src="https://www.youtube.com/embed/3oXZTy7hrAQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>This article will show you how to visualize, modify and save images in <em>Python, </em>more specifically in <em><a href="https://blog.finxter.com/matplotlib-full-guide/" target="_blank" rel="noreferrer noopener" title="Matplotlib — A Simple Guide with Videos">Matplotlib</a>. </em>In the following sections, we will see how to load images, how to modify some of their properties and finally how to save them.</p>



<h2 class="wp-block-heading">Long story short</h2>



<p>If you want to import an image and to display it in a <em>Matplotlib</em> window, the <em>Matplotlib</em> function <em>imread() </em>works perfectly. After importing the image file as an array, it is possible to create a <em>Matplotlib</em> window and the axes in which we can then display the image by using <em><a href="https://blog.finxter.com/matplotlib-imshow/" title="Matplotlib Imshow — A Helpful Illustrated Guide">imshow()</a>. </em>By changing some of the properties available within <em>imshow() </em>we can <em>&nbsp;</em>vary the color, the size and even decide to crop the displayed image. Once we are satisfied with the result from our modifications, the function <em>savefig() </em>allows to save the figure by specifying as input parameters the path in which we want the image to be stored. Exploiting some additional parameters of this latter function it is possible to decide whether to make the borders of the image transparent or even to delete them.</p>



<h2 class="wp-block-heading">Main functions that are used:</h2>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><code><strong>imshow</strong></code></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td><strong><em>Syntax:</em></strong></td><td><code>imshow()</code></td><td></td></tr><tr><td><strong><em>Parameters:</em></strong></td><td><code>X</code><em> (array-like image)</em></td><td><em>the image data file</em></td></tr><tr><td></td><td><code>cmap</code><em> (str)</em></td><td><em>colormap</em></td></tr><tr><td></td><td><code>alpha</code><em> (float)</em></td><td><em>transparency of the image</em></td></tr><tr><td></td><td><em><code>aspect</code> {&#8216;equal&#8217;, &#8216;auto&#8217;}</em></td><td><em>aspect ratio of the axes</em></td></tr><tr><td></td><td><code>vmin, vmax</code><em> (float)</em></td><td><em>minimum and maximum values for the color range</em></td></tr><tr><td><strong><em>Return Value</em></strong></td><td><code>None</code></td><td></td></tr></tbody></table></figure>



<p>More information here: <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html" target="_blank" rel="noreferrer noopener">https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html</a>.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td><code><strong>savefig</strong></code></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td><strong><em>Syntax:</em></strong></td><td><code>savefig()</code></td><td></td></tr><tr><td><strong><em>Parameters:</em></strong></td><td><em><code>fname</code> (str or path)</em></td><td><em>path in which you want the file to be saved</em></td></tr><tr><td></td><td><em><code>bbox_inches</code> (str)</em></td><td><em>Bounding box in inches. If &#8220;tight&#8221;, try to figure out the tight bbox of the figure</em></td></tr><tr><td></td><td><code>pad_inches</code><em> (float)</em></td><td><em>Amount of padding around the figure when bbox_inches is &#8216;tight&#8217;.</em></td></tr><tr><td><strong><em>Return Value</em></strong></td><td><code>None</code></td><td></td></tr></tbody></table></figure>



<p>More information here: <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html" target="_blank" rel="noreferrer noopener">https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html</a>.</p>



<h2 class="wp-block-heading">Importing an Image into Your Script</h2>



<p>We start the tutorial by importing the image in our script, in this way we will be able to take further actions and hence modify its appearance. To do this, we exploit the <em>Matplotlib </em>function <em>imread(), </em>which reads an image from a file into an array (official documentation: <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imread.html">https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imread.html</a>). </p>



<p>The function takes as the only input parameter the path of the image file that we want to import. </p>



<p>The image file is converted into a M x N x 3 (in the case of a RGB image) array with M and N standing for the number of pixels for the width and height, respectively. In the case of a RGB image, each M<sub>i</sub>N<sub>j</sub> subarray will contain 3 numbers corresponding to the combination of Red Green Blue values that identify that specific color; in the case of RGBA images, we would have a M x N x 4 array. </p>



<p>In the following code lines, we import the <em>Matplotlib </em>library and we assig to the variable “pic” the array describing the image file that we wanted to import.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

url = r"file_path"
pic = plt.imread(url)
print(pic)
</pre>



<p>The result of the printing command will display in your terminal a 3D array describing the image file that you uploaded.</p>



<h2 class="wp-block-heading">Obtaining the Image Size</h2>



<p>It is possible to know how many pixels compose our image and what type of color code it uses, by just applying the method <em>.shape() </em>to the variable in which we stored the array describing the image file. Indeed, by getting the array shape, we will obtain the different dimensions of the array, since each subarray will represent a pixel with its color values, we will get an indication of the exact number of pixel that make up our image (i.e. each element corresponds to a pixel).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># get image pixels
print(pic.shape)
>> (2559, 4550, 3)
</pre>



<p>In our case, we have an image that is 2559 pixels high, 4550 pixels wide and is defined according to a RGB color scheme (from the 3 values in the last array dimension).</p>



<h2 class="wp-block-heading">Display Images in Matplotlib</h2>



<p>In this section we will see how to display an image file in a matplotlib window; the procedure is extremely easy and really similar to the one that is used for plotting a normal graph. We start by creating the <a href="https://blog.finxter.com/customize-multiple-subplots-in-matplotlib/" target="_blank" rel="noreferrer noopener" title="How to Customize Multiple Subplots in Matplotlib">matplotlib figure</a> and the <a href="https://blog.finxter.com/matplotlib-how-to-change-subplot-sizes/" target="_blank" rel="noreferrer noopener" title="Matplotlib – How to Change Subplot Sizes">axes</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># display the image in a mpl figure
fig = plt.figure()
ax = fig.subplots()
</pre>



<p>At this point, we use the <em>Matplotlib </em>function <em>imshow() </em>to display the image within the just created axes. The <em>imshow() </em>function accepts as its main input parameter the variable referring to the image file, which in our case, is “pic”. The result from the following code lines is then displayed in Figure 1.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax.imshow(pic)
plt.show()
</pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="532" height="302" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-88.png" alt="" class="wp-image-27135" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-88.png 532w, https://blog.finxter.com/wp-content/uploads/2021/03/image-88-300x170.png 300w" sizes="auto, (max-width: 532px) 100vw, 532px" /><figcaption><strong><em>Figure 1: </em></strong>After creating a matplotlib figure and the axes, <em>imshow() </em>allows displaying the image file within the axes of the figure.</figcaption></figure>
</div>


<p></p>



<h2 class="wp-block-heading">Changing the Properties of the Displayed Image</h2>



<p>By specifying other input parameters within the <em>imshow() </em>function it is possible to modify some of the properties of the displayed image, like the size, the color and its transparency. </p>



<p>To be able to modify the just mentioned properties, we have to <a href="https://blog.finxter.com/daily-python-puzzle-list-indexing/" title="List Indexing" target="_blank" rel="noreferrer noopener">index </a>the pixels on which we want to apply any changes, if we want to modify the entire image, we just have to index all the pixels (in this case, this means writing <em>pic[:, :, 1]</em>). The first property that we will change is the transparency of the image; we can do this by changing the value of the <em>alpha </em>parameter (from to 0 to 1). </p>



<p>We can also change the <a href="https://blog.finxter.com/heatmaps-with-seaborn/" title="Creating Beautiful Heatmaps with Seaborn" target="_blank" rel="noreferrer noopener">color map</a> that is used in the image, for example using a “gray” color map will turn our color image into a black and white picture. This thing can be done by modifying the parameter <em>cmap </em>(here you can find all the possible color maps available for <em>Matplotlib: </em><a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html" target="_blank" rel="noreferrer noopener">https://matplotlib.org/stable/tutorials/colors/colormaps.html</a>). </p>



<p>If we want to change the color range used within the selected color map, we could modify the values of the parameters <em>vmin </em>and <em>vmax </em>for tuning the highest and lowest values of the color range. If we don’t specify these two parameters, the whole color range will be used for displaying the image. </p>



<p>In addition to changing the color properties, we can also modify the aspect ratio of the image pixels; this is an important topic to keep in mind, especially if we want to change the size of the axes of the figure. This can be done by exploiting the parameter <em>aspect; </em>we can choose between two different options <em>auto </em>or <em>equal. </em>Using<em> auto </em>will keep the axes fixed and the aspect ratio of the pixels is adjusted accordingly, generally resulting in non-square pixels. On the other hand, <em>equal </em>ensures an aspect ratio of 1 for the pixels in the image, meaning square pixels. </p>



<p>You can find additional information about the <em>imshow() </em>function and all its properties in the official documentation page: <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html">https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html</a>. In the following code line, we assign to the variable <em>f</em> the image file and we change all the above-mentioned properties.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">f = ax.imshow(pic[:, :, 1], alpha=0.5, cmap='gray',  vmin=0, vmax=500, aspect='auto')</pre>



<p>It is also possible to add a color bar next to the image by<strong><em> </em></strong>applying the method <em><a href="https://blog.finxter.com/matplotlib-3d-plot-full/" target="_blank" rel="noreferrer noopener" title="Matplotlib 3D Plot [Tutorial]">colorbar()</a> </em>to the figure<em>.</em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">f = ax.imshow(pic[:, :, 1], alpha=0.5, cmap='gray',  vmin=0, vmax=500, aspect='auto')</pre>



<p>The final result is displayed in Figure 2; notice that since we set <em>aspect = ‘auto’, </em>the aspect ratio of the pixels has changed hence producing an image whose shape is slightly different (see the video for a better example) from the one in Figure 1.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="594" height="325" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-89.png" alt="" class="wp-image-27139" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-89.png 594w, https://blog.finxter.com/wp-content/uploads/2021/03/image-89-300x164.png 300w" sizes="auto, (max-width: 594px) 100vw, 594px" /><figcaption><strong><em>Figure 2: </em></strong>Changing the properties within the <em>imshow() </em>function allowed for changing the image color scale and pixel aspect ratio.</figcaption></figure>
</div>


<p></p>



<h2 class="wp-block-heading">Changing the Axes Range and Visibility</h2>



<p>As you can see from the previous figures, all the axes and the tick labels are still present and visible in the plotting window. In the case we would like to remove them and hence have just the image plotted within the <em>Matplotlib </em>window, we can disable the axes by using <em>.axis(‘off’). </em>If we are also interested in plotting just a portion of the image, we can do it by adjusting the value of the maximum x and y values to be displayed on each of the axes. All these commands are displayed in the following code lines:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># changing the axes properties
ax.set_xlim(0, 2500)
ax.set_ylim(2500, 0)
ax.axis('off')
</pre>



<p>You can notice that we chose to display the image for its entire height but with a width going from 0 to the value 2500. Also notice that the coordinates of the y-axis are given in the inverted order; this is because the y-axis of the image goes from the top to the bottom of the figure. If you gave the limits of the y-axis in the opposite order, the imaged will be flipped. The final result is displayed in Figure 3.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="339" height="326" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-90.png" alt="" class="wp-image-27142" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-90.png 339w, https://blog.finxter.com/wp-content/uploads/2021/03/image-90-300x288.png 300w" sizes="auto, (max-width: 339px) 100vw, 339px" /><figcaption><strong><em>Figure 3: </em></strong>It is possible to crop the image by just changing the values of the maximum x and y coordinates along the axes. In order to display only the image, it is then possible to set to “off” the axes visibility.</figcaption></figure>
</div>


<p></p>



<h2 class="wp-block-heading">Saving the Image File</h2>



<p>Once we finished to edit our image, we can save it by using the <em>Matplotlib </em>function <em>savefig(). </em>The only mandatory input parameter is the path to which we want to save the image. In the case we want to save the image without any white border, we can specify the two optional parameters <em>bbox_inches </em>(setting it to “tight”) and <em>pad_inches </em>(setting it equal to zero). With the first option we make the border of the figure to adapt to the size of the image, with the second one we set to zero the amount of border around the figure (we first have to set to “tight” the property <em>bbox_inches</em>).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">plt.savefig(r"C:\Users\Andrea\Desktop\newimage.jpg", bbox_inches='tight', pad_inches=0)</pre>



<h2 class="wp-block-heading">Conclusions&nbsp; <em>&nbsp;</em></h2>



<p>In this article, we just learned how to import and modify an image file by using <em>Matplotlib. </em>First of all, we imported the image file within a <em>Matplotlib</em> window; then by using the appropriate functions, it was possible to display the image, change its color, its size and aspect ratio. In the end we also saw how to save the modified image into a new image file. All these procedures represent a really easy and fast solution for a quick adjustment of images within a <em>Python </em>session.</p>



<h2 class="wp-block-heading">Programmer Humor &#8211; Blockchain</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="280" height="394" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png" alt="" class="wp-image-457795" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png 280w, https://blog.finxter.com/wp-content/uploads/2022/07/image-31-213x300.png 213w" sizes="auto, (max-width: 280px) 100vw, 280px" /><figcaption><em>&#8220;Blockchains are like grappling hooks, in that it&#8217;s extremely cool when you encounter a problem for which they&#8217;re the right solution, but it happens way too rarely in real life.&#8221;</em> <strong>source </strong>&#8211; <a href="https://imgs.xkcd.com/comics/blockchain.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/blockchain.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure>
</div><p>The post <a href="https://blog.finxter.com/display-modify-and-save-images-with-matplotlib/">How to Display, Modify and Save Images in Matplotlib</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Conversions: Decimal + Binary + Octal + Hex</title>
		<link>https://blog.finxter.com/python-conversions-decimal-binary-octal-hex/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Tue, 23 Mar 2021 09:24:24 +0000</pubDate>
				<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=26752</guid>

					<description><![CDATA[<p>This article will walk you through the different numerical systems that can be used to represent numbers in Python. The system that we usually use in our daily life is the decimal system and, as the name suggests, it is based on 10 basic digits from which we can obtain all the numbers. Out of ... <a title="Python Conversions: Decimal + Binary + Octal + Hex" class="read-more" href="https://blog.finxter.com/python-conversions-decimal-binary-octal-hex/" aria-label="Read more about Python Conversions: Decimal + Binary + Octal + Hex">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-conversions-decimal-binary-octal-hex/">Python Conversions: Decimal + Binary + Octal + Hex</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Conversions: Decimal + Binary + Octal + Hex" width="937" height="527" src="https://www.youtube.com/embed/OHUzQcNurR0?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>This article will walk you through the different numerical systems that can be used to represent numbers in <em>Python</em>. </p>



<p>The system that we usually use in our daily life is the decimal system and, as the name suggests, it is based on 10 basic digits from which we can obtain all the numbers. </p>



<p>Out of our ordinary life, other numerical systems are used, especially in the computer world. As you may already know, all computers are based on a binary system; however, sometimes even the octal (which has 8 basic digits) and the hexadecimal (based on 16 digits) systems are used for specific applications. </p>



<p>In the following sections you will see how to use some <a href="https://blog.finxter.com/python-built-in-functions/" target="_blank" rel="noreferrer noopener" title="Python Built-In Functions"><em>Python </em>built-in functions</a> to convert from one numerical system to the other.</p>



<h2 class="wp-block-heading">Long Story Short</h2>



<p><em>Python </em>provides some built-in functions for converting numbers from one numerical system to another. More specifically, these functions allow converting integer numbers to the:</p>



<ul class="wp-block-list"><li>decimal system: <code><a href="https://blog.finxter.com/python-int-function/" target="_blank" rel="noreferrer noopener" title="Python int() Function">int()</a></code></li><li>binary system: <code><a href="https://blog.finxter.com/python-bin-function/" target="_blank" rel="noreferrer noopener" title="Python bin() Function">bin()</a></code></li><li>octal system: <code><a href="https://blog.finxter.com/python-oct-function/" target="_blank" rel="noreferrer noopener" title="Python oct() Function">oct()</a></code></li><li>hexadecimal system: <code><a href="https://blog.finxter.com/python-hex-function/" target="_blank" rel="noreferrer noopener" title="Python hex() Function — Not a Magic Trick">hex()</a></code></li></ul>



<p>In addition to these, the function <code>float.hex()</code><em> </em>allows converting floating-point numbers from the decimal to the hexadecimal system.</p>



<h2 class="wp-block-heading">The Decimal System</h2>



<p>The Decimal system is the numerical system that we use the most in our ordinary life (no coincidence with the fact that we have precisely ten fingers); it is based on 10 different digits that are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10, from which it is possible to obtain all the possible numbers that we need. Even if all the computer-based systems are based on the binary system (and later we will see why), the user interface of most programs like <em>Python, </em>uses the decimal system to store values and perform mathematical operations.</p>



<h2 class="wp-block-heading">The Binary System</h2>



<p>The binary system represents the foundation of all the computer-based systems that are in use nowadays; as the name suggest, it exploits two different digits, 1 and 0, to build up all the possible number combinations. The choice of the two digits simply derives from how a system like a computer ultimately works; if you think about it, all the tasks that your computer is able to perform can be linked to a series of ON/OFF signals from which the digits 1 and 0, respectively. In this way, just by using zeroes and ones, the binary system represents all the available numbers.</p>



<h3 class="wp-block-heading">Do you know how the Binary to Decimal conversion works?</h3>



<p>Converting from binary to decimal is pretty easy, this section will show you, using an example, how this can be done manually (if you are not interested, just skip it and go directly to the code part). Since the binary system is based on two digits, to convert a binary number into a decimal number we will have to exploit powers of 2. As an example, let’s see how to convert the binary number 11011 into its decimal representation.</p>



<p>First of all, each digit position will represent the power of two that will be used in the conversion:</p>



<pre class="wp-block-preformatted"> 1&nbsp; 1&nbsp; 0&nbsp; 1&nbsp; 1
 2<sup>4 </sup>2<sup>3 </sup>2<sup>2 </sup>2<sup>1 </sup>2<sup>0</sup> </pre>



<p>At this point, each power of two should be multiplied by the respective binary digit (either 1 or 0) and summed with the others, in this case we get:</p>



<pre class="wp-block-preformatted">1 * 2<sup>4</sup> + <sup>&nbsp;</sup>1 * 2<sup>3 </sup>+ 0 * 2<sup>2</sup> + 1 *2<sup>1</sup> + 1 *2<sup>0</sup> = 16 + 8 + 2 + 1 = 27</pre>



<h3 class="wp-block-heading">How to convert from Binary to Decimal and vice versa in Python</h3>



<p>To convert from one numerical system to another in <em>Python </em>is extremely easy, we just have to remember which function should be used and what to pass as input parameter. To represent a binary number in <em>Python</em>, we have to use the prefix “0b” which tells the system that the digits that follows, actually represent a binary number. You can try this by printing the following code lines:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">num = 10
num_bin = 0b10
print(num, num_bin)
# 10 2</pre>



<p>in the binary system, 10 represents the number 2; the output of the printing command on the variable <code>num_bin</code><em> </em>will be “2”; this is because <em>Python, </em>by default, prints the result using the decimal system. However, if we want to perform some mathematical operations, we have to first convert the number into a decimal number and this can be done by using the function <code>int()</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">bin_to_dec = int(0b10)  
print(bin_to_dec)
# 2</pre>



<p>On the other hand, to convert a decimal number to the binary notation, the appropriate function is <code>bin()</code><em>, </em>you can try to check personally if the result of the following code lines is correct.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dec_to_bin = bin(2234)
print(dec_to_bin)
# 0b100010111010</pre>



<h2 class="wp-block-heading">The Octal System</h2>



<p>As suggested by the name, the Octal system is based on eight basic digits, from 0 to 7. A curious fact is that some Native Americans tribes adopt&nbsp; the Octal system because they count using the spaces between the fingers or the knuckles of their closed fists (if you want to know more about this: <a href="https://en.wikipedia.org/wiki/Yuki_language" target="_blank" rel="noreferrer noopener" title="https://en.wikipedia.org/wiki/Yuki_language">Yuki language</a> (spaces between fingers), <a href="https://en.wikipedia.org/wiki/Pame_languages" target="_blank" rel="noreferrer noopener" title="https://en.wikipedia.org/wiki/Pame_languages">Pamean languages</a> (knuckles of closed fists)). The procedure used to convert a number in the Octal system is similar to the one used above. In <em>Python, </em>octal numbers are identified by the prefix “0o” and the function that is used to do the conversion is called <em><code>oct()</code></em>; the input, of course, is the decimal number that we want to convert.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dec_to_oct = oct(57)
print(dec_to_oct)
# 0o71</pre>



<p>The opposite operation can still be performed by using again the <code>int()</code><em> </em>function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">oct_to_dec = int(0o71)
print(oct_to_dec)
# 57</pre>



<p>As you may imagine, it is also possible to convert directly from binary to octal and vice versa. The functions at play are always the same, let’s see how to convert the binary 0b100010111010 in the octal system:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">bin_to_oct = oct(0b100010111010)
print(bin_to_oct)
# 0o4272</pre>



<p>Do you remember which was the equivalent for this number in the decimal notation? We can use <em>Python </em>to get the answer instantaneously; however, the results that we get from functions like <code>bin()</code><em> or </em><code>oct()</code><em> </em>are expressed in the string format, this means that if we enter them as input parameters of the function <code>int()</code><em>, </em>we get an error, stating that <em>Python</em> cannot convert a string into a number. To solve this issue we can specify the format of the input parameter in the following way:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">oct_to_dec = int(bin_to_oct, 8)
print(bin_to_oct, oct_to_dec)
# 0o4272 2234</pre>



<p>In the binary case, we would have used “2”.</p>



<h2 class="wp-block-heading">The Hexadecimal System</h2>



<p>The Hexadecimal system is based on 16 digits, since we only have 9 different numbers in our decimal system, also letters are employed, namely:</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Hexadecimal</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td><td>F</td><td>G</td></tr><tr><td>Decimal</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td><td>12</td><td>13</td><td>14</td><td>15</td><td>16</td></tr></tbody></table></figure>



<p>The conversion to the hexadecimal system is analogous to the one illustrated for the octal system, the only difference is that this time the powers will have base 16. In this way, 17 becomes 11 in the hexadecimal notation. To denote a hexadecimal number in <em>Python, </em>we have to use the prefix “0x”. The function that allows us converting from one numeric system to the hexadecimal one is called <code><a href="https://blog.finxter.com/python-hex-function/" target="_blank" rel="noreferrer noopener" title="Python hex() Function — Not a Magic Trick">hex()</a></code><em> </em>and accepts as input parameter any integer number expressed in one of the aforementioned numeric systems.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dec_to_hex = hex(2234)
print(dec_to_hex)
# 0x8ba

bin_to_hex = hex(0b100010111010)
print(bin_to_hex)
# 0x8ba

oct_to_hex = hex(0o4272)
print(oct_to_hex)
# 0x8ba</pre>



<p></p>



<h2 class="wp-block-heading">What about floating numbers?</h2>



<p>As you may have noticed, all the mentioned functions do accept as input for the conversion only integer numbers; this is because the expression of <a href="https://blog.finxter.com/python-hex-to-float-conversion/" data-type="post" data-id="856968" target="_blank" rel="noreferrer noopener">floating-point</a> numbers is not unique, there are different notations which could be dependent on the computing system that we are using. </p>



<p>However, for the case of Hexadecimal numbers, <em>Python </em>provides a <a href="https://blog.finxter.com/python-built-in-functions/" target="_blank" rel="noreferrer noopener" title="Python Built-In Functions">built-in function </a>to convert floating numbers from the decimal system to the hexadecimal system. The function is called <code>float.hex()</code><em> </em>and accepts as input parameter the floating number in the decimal notation. The following code lines provide an example of its use.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">float_dec_to_hex = float.hex(416.8)
print(float_dec_to_hex)
# 0x1.a0ccccccccccdp+8</pre>



<p>As you can see, the notation that is used to express the answer is quite different from the one used for the integer numbers; this is because in these cases <em>Python </em>uses the scientific notation. The letter “p” stands for “times 2 to the power of” and “+8” is the exponent, while the bullet is then the decimal point. This is just one of the possible notation for expressing floating-point numbers in different notations; if you are interested in how it works, here are some useful links: </p>



<ul class="wp-block-list"><li>i) <a href="https://en.wikipedia.org/wiki/Hexadecimal">https://en.wikipedia.org/wiki/Hexadecimal</a>, </li><li>ii)&nbsp; <a href="https://stackoverflow.com/questions/54947861/32-bit-ieee-754-single-precision-floating-point-to-hexadecimal">https://stackoverflow.com/questions/54947861/32-bit-ieee-754-single-precision-floating-point-to-hexadecimal</a> .</li></ul>



<h2 class="wp-block-heading">Conclusions</h2>



<p>In the article, we took a tour through the most widely used numerical systems and the functions that <em>Python </em>offers for converting from one notation to the other. When programming, it is good practice to be able at least to recognize the employed numerical system, in order to decide which of the above-mentioned functions to use for converting into the numerical system that is currently in use.</p>
<p>The post <a href="https://blog.finxter.com/python-conversions-decimal-binary-octal-hex/">Python Conversions: Decimal + Binary + Octal + Hex</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Customize Multiple Subplots in Matplotlib</title>
		<link>https://blog.finxter.com/customize-multiple-subplots-in-matplotlib/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Mon, 01 Mar 2021 19:26:39 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=24762</guid>

					<description><![CDATA[<p>This article will cover a specific issue that most Python users encounter when using Matplotlib for plotting their graphs. I am talking about defining multiple subplots and being able to access and change their properties individually. In the following sections, we will see how to use the Matplotlib function .subplots() for generating multiple subplots and ... <a title="How to Customize Multiple Subplots in Matplotlib" class="read-more" href="https://blog.finxter.com/customize-multiple-subplots-in-matplotlib/" aria-label="Read more about How to Customize Multiple Subplots in Matplotlib">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/customize-multiple-subplots-in-matplotlib/">How to Customize Multiple Subplots in Matplotlib</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This article will cover a specific issue that most Python users encounter when using <em><a href="https://blog.finxter.com/matplotlib-full-guide/" title="Matplotlib — A Simple Guide with Videos" target="_blank" rel="noreferrer noopener">Matplotlib </a></em>for plotting their graphs. I am talking about defining multiple subplots and being able to access and change their properties individually. </p>



<p>In the following sections, we will see how to use the <em>Matplotlib</em> function <em><code><a href="https://blog.finxter.com/matplotlib-subplots/" title="Matplotlib Subplots – A Helpful Illustrated Guide" target="_blank" rel="noreferrer noopener">.subplots()</a></code></em> for generating multiple subplots and how to define properties like the labels of the axes, the title, and the grid of each of them both separately and simultaneously.</p>



<p>I explained this article in the following video tutorial:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Modify Subplots" width="937" height="527" src="https://www.youtube.com/embed/5Hx7EcSWT_g?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Importing Libraries</h2>



<p>Since we will just create some subplots and modify some of their properties, the only library that will be used throughout the entire example is <em>Matplotlib; </em>more specifically, we import the <em><code>Matplotlib.pyplot</code> </em>package to be able to plot and modify our plotting windows.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt</pre>



<h2 class="wp-block-heading">Creating the Plotting Window and Defining the Subplots</h2>



<p>The first step towards the creation of a <em>Matplotlib</em> plot is the definition of a plotting window, i.e. the window that will be displayed after running the code and that will contain all the subsequently defined plots. To do this, we use the <em>matplotlib </em>function <em><code>.figure()</code> </em>and we assign its value to the variable “<code>fig</code>”. We do not specify any input parameter; however, it is possible to modify the size of the figure, its <a href="https://blog.finxter.com/how-to-plot-matplotlibs-color-palette-and-choose-your-plot-color/" target="_blank" rel="noreferrer noopener" title="How to Plot Matplotlib’s Color Palette — and Choose Your Plot Color?">color</a>, and some other properties; you can find the official documentation at <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html" target="_blank" rel="noreferrer noopener" title="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html">this link</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fig = plt.figure()</pre>



<p>Once created the plotting window, we have to define the subplots; this can be done by using the function <code>.subplots()</code><em>, </em>applied to the previously defined figure (i.e. the variable “<code>fig</code>”). If we do not pass any input parameter, this function will generate a single subplot while if we want it to display multiple subplots, we have to specify the number of rows and columns in which we want to divide the plotting window. These input parameters are called “<code>nrows</code>” and ”<code>ncols</code>”; however, we can directly address them by simply typing the two respective numbers. </p>



<p>Other useful parameters are <code>sharex</code><em> </em>and<em> <code>sharey</code>, </em>if we put them equal to True, the generated subplots will share the <code>x</code> and/or the <code>y</code> axes. For this example, we define four subplots, displayed along two rows and two columns; and we assign them to the variable “<code>ax</code>”. The following code line describes the procedure. We also use the function <code>.subplots_adjust()</code><em> </em>for changing the separation between the four subplots, specifically by setting to 0.5 the value of the parameters <code>hspace </code>and <code>wspace </code>(corresponding to the vertical and horizontal separation, respectively).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax = fig.subplots(2, 2)
fig.subplots_adjust(hspace=0.5, wspace=0.5)</pre>



<p>The obtained result is displayed in Figure 1, which shows the four subplots initialized in a 2&#215;2 grid inside the matplotlib window.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="536" height="281" src="https://blog.finxter.com/wp-content/uploads/2021/03/image.png" alt="" class="wp-image-24766" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image.png 536w, https://blog.finxter.com/wp-content/uploads/2021/03/image-300x157.png 300w" sizes="auto, (max-width: 536px) 100vw, 536px" /></figure></div>



<p><strong><em>Figure 1:</em></strong> Initialization of four subplots, distributed in a 2&#215;2 grid within the <em>matplotlib</em> window.</p>



<h2 class="wp-block-heading">Changing the Properties of Individual Subplots</h2>



<p>Now that we created our four subplots, we proceed further and change some of the properties of individual plots. This is a really easy task; indeed, thanks to the strategy that we adopted for the definition of the subplots, now the variable “<code>ax</code>” is a 2&#215;2 array and hence allows accessing each of its elements (each subplot) by simple <a href="https://blog.finxter.com/daily-python-puzzle-list-indexing/" title="List Indexing" target="_blank" rel="noreferrer noopener">indexing</a>. </p>



<p>In our case, the subplot on the upper left corner is the element <code>[0, 0]</code>, the one in the upper right corner the <code>[0, 1]</code>, on the bottom left we have the <code>[1, 0]</code> and on the bottom right the <code>[1, 1]</code>. We can now try to add a title to the subplot in the bottom left corner, this can be done by applying the method <em><code>.set_title()</code></em> to the element <em><code>ax[1, 0]</code></em> and by passing as a string the title that we want to add:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ax[1, 0].set_title('Plot n° 3')</pre>



<p>The final result is displayed in Figure 2; as you can see, we added a title solely to the bottom left subplot, while the others are still lacking it.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="537" height="277" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-1.png" alt="" class="wp-image-24770" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-1.png 537w, https://blog.finxter.com/wp-content/uploads/2021/03/image-1-300x155.png 300w" sizes="auto, (max-width: 537px) 100vw, 537px" /></figure></div>



<p><strong><em>Figure 2:</em></strong> By applying the method <code>.set_title()</code> to the <code>[1, 0]</code> element of the <em><code>ax</code> </em>array, we added a title solely to the subplot in the bottom left corner.</p>



<p>In an analogous way, we can access and change the properties of all the others individual subplots that make up our figure. To this purpose, some of the most frequently used methods are:</p>



<ul class="wp-block-list"><li><em><code>.grid()</code> </em>for enabling the grid on your plot and for changing its properties (like color and linewidth)</li><li><em><code>.set_xlabel</code> </em>or <em><code>set_ylabel()</code> </em>for setting the title of the <code>x</code> and <code>y</code> axes, respectively</li><li><em><code>.set_facecolor()</code> </em>for changing the background color of each subplot</li></ul>



<h2 class="wp-block-heading">Automatically Setting the Properties of All Subplots</h2>



<p>Let’s now suppose that we want to initialize some of the previously listed properties for all of the subplots present in our window. Even if it was not a difficult task, repeating that step for multiple properties and for multiple plots could be repetitive and time consuming (as well as annoying). </p>



<p>To solve this issue, it is possible to exploit <em><a href="https://blog.finxter.com/python-loops/" title="Python Loops" target="_blank" rel="noreferrer noopener">for loops</a> </em>for defining and/or changing some of the properties of all the subplots automatically and rapidly. Indeed, since the variable <em><code>ax </code></em>has been initialized as a 2&#215;2 array, we can hence use two nested <em>for loops </em>for accessing each subplot one at a time and changing all its properties in an iterative fashion. In the following code lines, we will use two nested <em>for loops </em>for accessing each of the subplots and changing properties like the title, the grid, the background color and the axes labels. </p>



<p>Before entering the <em>for loops, </em>we define the variables “<code>rows</code>” and “<code>cols</code>” which indicates the total number of rows and columns the window is divided into; they will be then used as escape value for stopping the iterations inside the loops. We also define an index “<code>n</code>”, which will be used for assigning the number to each plot title.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">rows, cols = 2, 2
n = 1
for i in range(rows):
    for j in range(cols):
        ax[i, j].grid(color='w', linewidth=1)
        ax[i, j].set_ylabel('Y axis')
        ax[i, j].set_xlabel('X axis')
        ax[i, j].set_facecolor("grey")
        ax[i, j].set_title('Plot n° ' + str(n))
        n += 1
plt.show()
</pre>



<p>As you can see from the code lines, each of the subplots will have a white grid, two labels for the y and x axis, respectively, a grey background and a title stating “Plot n° (number of the plot)”, where the number of the plot is dictated by the value of the index “n”. The final result is displayed in Figure 3.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="540" height="296" src="https://blog.finxter.com/wp-content/uploads/2021/03/image-2.png" alt="" class="wp-image-24772" srcset="https://blog.finxter.com/wp-content/uploads/2021/03/image-2.png 540w, https://blog.finxter.com/wp-content/uploads/2021/03/image-2-300x164.png 300w" sizes="auto, (max-width: 540px) 100vw, 540px" /></figure></div>



<p><strong><em>Figure 3:</em></strong> Using two nested <em>for loops </em>we were able to change the properties of all the four subplots automatically, without the need of repeating all the steps for each of them.</p>



<h2 class="wp-block-heading">Full Code</h2>



<p>Here&#8217;s the full code from this tutorial:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt

fig = plt.figure()
rows, cols = 2, 2
ax = fig.subplots(nrows=rows, ncols=cols)
fig.subplots_adjust(hspace=0.5, wspace=0.5)
# adding a title to an individual subplot
ax[1, 0].set_title('Plot n° 3')
# automatically set the properties for all the subplots
n = 1
for i in range(rows):
    for j in range(cols):
        ax[i, j].grid(color='w', linewidth=1)
        ax[i, j].set_ylabel('Y axis')
        ax[i, j].set_xlabel('X axis')
        ax[i, j].set_facecolor('grey')
        ax[i, j].set_title('Plot n° ' + str(n))
        n += 1
plt.show()</pre>



<h2 class="wp-block-heading">Conclusions</h2>



<p>In this article we saw how to access every single subplot present in a matplotlib window; in the first part we manually added a title to just one of the four subplots, in the second part we exploited two nested <em>for loops </em>to iterate through all the subplots and changing all of their properties simultaneously and automatically.&nbsp;</p>
<p>The post <a href="https://blog.finxter.com/customize-multiple-subplots-in-matplotlib/">How to Customize Multiple Subplots in Matplotlib</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Calculate Percentiles in Python</title>
		<link>https://blog.finxter.com/how-to-calculate-percentiles-in-python/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Mon, 08 Feb 2021 13:15:18 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[NumPy]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Scripting]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=23370</guid>

					<description><![CDATA[<p>This article deals with calculating percentiles. Percentiles are statistical indicators that are used to describe specific portions of a sample population. The following sections will explain what percentiles are, what they are used for and how to calculate them, using Python. As you will see, Python allows solving this problem in multiple ways, either by ... <a title="How to Calculate Percentiles in Python" class="read-more" href="https://blog.finxter.com/how-to-calculate-percentiles-in-python/" aria-label="Read more about How to Calculate Percentiles in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-percentiles-in-python/">How to Calculate Percentiles in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This article deals with calculating percentiles. Percentiles are statistical indicators that are used to describe specific portions of a sample population. The following sections will explain what percentiles are, what they are used for and how to calculate them, using Python. As you will see, Python allows solving this problem in multiple ways, either by manually defining a function or by exploiting <em><a href="https://blog.finxter.com/numpy-tutorial/" title="NumPy Tutorial – Everything You Need to Know to Get Started" target="_blank" rel="noreferrer noopener">Numpy</a></em>.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Calculate Percentiles in Python: np.percentile()" width="937" height="527" src="https://www.youtube.com/embed/FJPy3yTtqlQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">What Are Percentiles?</h2>



<p>Percentiles are statistical indicators that are often used to identify a certain part of a sample population. More precisely, we use a percentile in order to indicate the value (of the variable that is under consideration) below which a specific percentage of the sample population falls. For example, if we consider the height distribution of all the English people living in UK; by saying that the height value of <em>180 cm</em> identifies the 65<sup>th</sup> percentile, it means that the 65% of all the English people living in UK are shorter than <em>180 cm</em>. As you can imagine, percentile are commonly used in lots of statistical studies and when reporting results of surveys or measurements on large populations.</p>



<h2 class="wp-block-heading">How to Calculate Percentiles?</h2>



<p>Let’s assume to have collected the height of <em>n = 58</em> people; in order to evaluate the percentiles referred to this distribution, the first step is to sort all the values in ascending order. At this point, suppose we are asked to calculate the 75<sup>th</sup> percentile of the distribution; we calculate the so-called rank <em>k = percentile/100</em>. In this case, <em>k = 75/100 = 0.75</em>. Now we have to multiply the rank for the total number of samples in the distribution (n, in this case 58); we hence obtain <em>k x n = 0.75 x 58 = 43.5</em>. Since the result is not a whole number, we approximate the value to the nearest whole number (44 in this case). The next step consists in finding the height value corresponding at the 44<sup>th</sup> position within the sample distribution; that value corresponds to the 75<sup>th</sup> percentile. In the case the result of <em>k x n</em> is a whole number, we proceed further by directly finding the corresponding value in the sample distribution; that is already our percentile. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>



<h2 class="wp-block-heading">Calculate Percentiles in Python</h2>



<p>Now that we know what percentiles are and how they can be calculated, we will see how <em>Python </em>makes this task very easy and quick. In the first part, we will solve the problem by defining a function that execute all the steps illustrated in the previous section while in the second part, we will exploit the <em>Numpy </em>built-in function <em>.percentile()</em>.</p>



<h2 class="wp-block-heading">Importing the Appropriate Libraries</h2>



<p>We start our script by importing the libraries that will be used throughout the example. </p>



<p>We need to import</p>



<ul class="wp-block-list"><li> <em><code><a href="https://blog.finxter.com/python-math-module/" title="Python Math Module [Ultimate Guide]" target="_blank" rel="noreferrer noopener">math</a></code> </em>for being able to round floating numbers to the nearest integer, </li><li><em><a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener" title="NumPy Tutorial – Everything You Need to Know to Get Started">Numpy </a></em>for the function <code>.percentile()</code><em>, </em>and </li><li><em><a href="https://blog.finxter.com/matplotlib-full-guide/" target="_blank" rel="noreferrer noopener" title="Matplotlib — A Simple Guide with Videos">Matplotlib </a></em>for the final part, in which we will plot the values of the percentiles on the distribution.</li></ul>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import math
import matplotlib.pyplot as plt</pre>



<h2 class="wp-block-heading">Writing a Python Function for Calculating Percentiles</h2>



<p>In this first section we will see how to build up a function for calculating the percentiles. The aim of this section is purely didactic, as you will see later on, <em>Python </em>offers built-in libraries that solve the task automatically. However, it’s always important to understand  how the problem gets solved and how a specific Python function works. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def my_percentile(data, percentile):
    n = len(data)
    p = n * percentile / 100
    if p.is_integer():
        return sorted(data)[int(p)]
    else:
        return sorted(data)[int(math.ceil(p)) - 1]
</pre>



<p>We start by calling our function <code>my_percentile</code>, it will take as input parameters the sample distribution and the percentile that we want to calculate. As detailed above, the first step is to evaluate the size of our distribution (n); then we compute the product “p” of the sample size and the rank<em>. </em></p>



<p>At this point we have to instantiate an <em><a href="https://blog.finxter.com/how-to-conditionally-select-elements-in-a-numpy-array/" title="How to Conditionally Select Elements in a Numpy Array?" target="_blank" rel="noreferrer noopener">if statement</a></em>, in order to separate the case in which <em>k x n </em>is a whole number from the case in which it is not. We exploit the <em>Python </em>method <em><code>.is_integer()</code> </em>to evaluate whether <em><code>p</code> </em>is a whole number; this method returns <code>True</code> in the positive case. </p>



<p>If <em><code>p.is_integer()</code> </em>returns <code>True</code>, we have to search for the <em>p-th</em> values in our distribution (sorted in ascending order). To sort the distribution in ascending order, we used the function <em><a href="https://blog.finxter.com/python-sorted-function/" title="Python sorted() Function" target="_blank" rel="noreferrer noopener"><code>sorted()</code></a></em> and pass as input parameter the distribution itself. The important thing to remember is to convert <em>p</em> from float (since it comes from the mathematical operation done in the previous line) to integer; otherwise you will get an error that says that the index value of the list should be an integer number. </p>



<p>We conclude by raising an <em>else statement </em>which covers the case in which the value of <em><code>p</code> </em>is not a whole number; in this case, by using the function <em><code>.ceil()</code> </em>(from the <em><code>math</code> </em>library)<em>, </em>we approximate the value of <code>p</code> to the nearest higher integer. </p>



<p>We then convert this number to an integer and subtract 1 in order to match the indexing used in the lists. The following code lines you can find all the steps explained so far, in this section.</p>



<h2 class="wp-block-heading">Calculating percentiles using our function</h2>



<p>To check whether our function works fine, we first have to define a distribution of values; to do that, we can exploit the <em>Numpy </em>function <code><a href="https://blog.finxter.com/create-a-list-of-random-numbers-the-most-pythonic-way/" target="_blank" rel="noreferrer noopener" title="Create a List of Random Numbers — The Most Pythonic Way">.random.randn()</a></code><em>, </em>which draws random values from the normal distribution, we just have to pass as input parameter the size of the array. We choose to create an array of 10000 values.  <em> </em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dist = np.random.randn(10000)</pre>



<p>Let’s now try to calculate the values of the 5<sup>th</sup>, 25<sup>th</sup>, 50<sup>th</sup>, 75<sup>th</sup> and 95<sup>th</sup> percentiles. We can hence build a list, called “<code>perc_func</code>” that contains all those percentiles, evaluated through our function. Before doing that, we define a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list </a>called “<code>index</code>” that contains the values of the percentiles that we are interested in. After that, we exploit <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">list comprehension</a>, to call the function <code>my_percentile()</code><em> </em>for each percentile defined in the list “<code>index</code>”.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">index = [5, 25, 50, 75, 95]
perc_func = [my_percentile(dist, i) for i in index]
</pre>



<p>At this point, the list “<code>perc_func</code>” should contain the values corresponding to all the percentiles listed in the list “<code>index</code>”.</p>



<h2 class="wp-block-heading">Calculating percentiles using Numpy.percentiles()</h2>



<p>Now that we know how to calculate percentiles of a distribution, we can also exploit the <em>Numpy </em>built-in function, to do it more rapidly and efficiently. </p>



<p>The <em><code>.percentile()</code></em> function takes as input parameters the sample distribution and the percentile that we are interested in. It also allows us to decide which method should be used in the case the product <em>n x k</em> is not a whole number; indeed, there is not just a single correct way to do that, previously we decided to approximate the value to the nearest integer; however we could also choose to approximate it to the closest higher/lower integer or to take the mean value between the lower and higher nearest integers. </p>



<p>All these options can be selected by choosing among these key words for the option “<code>interpolation</code>” <code>['linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’]. </code></p>



<p>You can find the complete documentation on the <code>.<em>percentile()</em></code><em> </em>function <a href="https://numpy.org/doc/stable/reference/generated/numpy.percentile.html" target="_blank" rel="noreferrer noopener" title="https://numpy.org/doc/stable/reference/generated/numpy.percentile.html">here</a>.</p>



<p>The different options may lead to slightly different results, we choose the option “<code>nearest</code>”, in order to match the method used in the function “<code>my_percentile</code>”. In a similar way to what we did in the previous section, we create a list called “<code>perc_numpy</code>” in which we store the values of the 5<sup>th</sup>, 25<sup>th</sup>, 50<sup>th</sup>, 75<sup>th</sup> and 95<sup>th</sup> percentiles, evaluated using the <em>Numpy</em>. The following code lines describe the just-explained procedures.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Using numpy for calculating percentiles
perc_numpy = [np.percentile(dist, i, interpolation='nearest') for i in index]
</pre>



<p>We can now <a href="https://blog.finxter.com/print-python-list/" target="_blank" rel="noreferrer noopener" title="Print a Python List Beautifully [Click &amp; Run Code]">print the two lists</a> and check whether the obtained results are equal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(perc_func)
print(perc_numpy)
</pre>



<h2 class="wp-block-heading">Plotting the Percentiles on the Distribution</h2>



<p>At the beginning of the article, we defined what percentiles represent. </p>



<p>Since statistical definitions can be rather difficult to grasp, we can display our distribution of values and see where the calculated percentiles are located in the distribution.</p>



<p>To do that, we exploit <em><a href="https://blog.finxter.com/best-matplotlib-cheat-sheet/" title="Best Matplotlib Cheat Sheet" target="_blank" rel="noreferrer noopener">Matplotlib </a></em>and the function <em><code>.axvline()</code>, </em>which allows plotting vertical lines on a plot. We place the function <em><code>axvline()</code> </em>into a <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">for loop </a>in order to create a vertical line for each percentile contained in the list “<code>perc_func</code>”. To better highlight the percentile lines, we use the color red.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Plotting 
plt.hist(dist, 50)
for i in range(len(index)):
    plt.axvline(perc_func[i], color='r')
plt.show()
</pre>



<p>The final result is displayed in <strong>Figure 1</strong>; as you can see, the 50<sup>th </sup>percentile is located right in the middle of the distribution, while the 95<sup>th </sup>percentile is the last line and corresponds to the value below which we can find the 95% of the sample population.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="547" height="316" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-39.png" alt="Percentile Python Plot" class="wp-image-23372" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-39.png 547w, https://blog.finxter.com/wp-content/uploads/2021/02/image-39-300x173.png 300w" sizes="auto, (max-width: 547px) 100vw, 547px" /></figure></div>



<p><strong><em>Figure 1: </em></strong>Representation of the normal distribution used in the example, with the vertical red lines corresponding (from left to right) to the 5<sup>th</sup>, 25<sup>th</sup>, 50<sup>th</sup>, 75<sup>th</sup> and 95<sup>th </sup>percentiles.</p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>In this article we learnt about <strong><em>percentiles</em></strong>, what they are, what they represent and how they can be used to describe a portion of a sample distribution. From their statistical definition, we developed a Python function for calculating the percentiles of a sample distribution. </p>



<p>After that, we explored the <em>Numpy </em>function <em><code>.percentile()</code></em> which allows calculating percentiles of a sample distribution in a super-fast and efficient way. </p>



<p>We then compared the results of the two methods and checked that they were identical. </p>



<p>In the end, we also showed graphically the percentiles, that we previously calculated, on the sample distribution, in order to have a better understanding of their actual meaning.</p>
<p>The post <a href="https://blog.finxter.com/how-to-calculate-percentiles-in-python/">How to Calculate Percentiles in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Symbolic Math with SymPy: Advanced Functions and Plots</title>
		<link>https://blog.finxter.com/symbolic-math-with-sympy-advanced-functions-and-plots/</link>
		
		<dc:creator><![CDATA[Andrea Ridolfi]]></dc:creator>
		<pubDate>Mon, 01 Feb 2021 15:52:22 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SymPy]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=22602</guid>

					<description><![CDATA[<p>This article will cover some advanced mathematical functions provided by the Sympy library. If you still have not read the first introductory article to Sympy, you can check it out here. Since most of the basic functions, like the ones for initiating a Sympy session on your terminal or for defining a function/variable, will not ... <a title="Symbolic Math with SymPy: Advanced Functions and Plots" class="read-more" href="https://blog.finxter.com/symbolic-math-with-sympy-advanced-functions-and-plots/" aria-label="Read more about Symbolic Math with SymPy: Advanced Functions and Plots">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/symbolic-math-with-sympy-advanced-functions-and-plots/">Symbolic Math with SymPy: Advanced Functions and Plots</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>This article will cover some advanced mathematical functions provided by the <em>Sympy </em>library. If you still have not read the first introductory article to <em>Sympy, </em><a href="https://blog.finxter.com/symbolic-math-with-sympy" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/symbolic-math-with-sympy">you can check it out here</a>. </p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Symbolic Math with SymPy: Advanced Functions and Plots" width="937" height="527" src="https://www.youtube.com/embed/TZr5iOxnMYw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Since most of the basic functions, like the ones for initiating a <em>Sympy</em> session on your terminal or for defining a function/variable, will not be covered in here. </p>



<p>In this article we will explore <strong>how to calculate derivatives, integrals and limits</strong> with <em>Sympy</em> and also <strong>how to plot graphs</strong> directly from the terminal. As already said in the previous article and video, the commands and functions that will be described in the following sections can be typed both in the script and in the terminal; I’ll use the terminal since it offers more intuitive and clearer data representation.</p>



<p>We start our code by importing the <em>Sympy</em> and <em><a href="https://blog.finxter.com/matplotlib-full-guide/" title="Matplotlib — A Simple Guide with Videos" target="_blank" rel="noreferrer noopener">Matplotlib </a></em>libraries; we will use the latter library to create plots from our data. If you do not know or you simply do not remember these procedures, just have a look at the<a href="https://blog.finxter.com/symbolic-math-with-sympy" target="_blank" rel="noreferrer noopener" title="https://blog.finxter.com/symbolic-math-with-sympy"> first article on <em>Sympy</em></a>, where it is also described how to initiate a <em>Sympy </em>session and define variables and functions().</p>



<h2 class="wp-block-heading">Derivatives and partial derivatives</h2>



<p>Calculating the derivatives of mathematical functions is a really common practice in most science related fields; by doing that, it is possible to identify the location of the maxima and minima of a function, i.e. the points in which it starts to increase/decrease. </p>



<p><em>Sympy </em>allows to solve this task in a very immediate way; the function that is used to this purpose is called <em>diff(), </em>from “differential”. The function <em>diff()</em>, takes as input parameter the function that we want to derivate. In the following code lines, we define a function, “f”, and we calculate its first derivative.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> f = 3*x**2 + 4*x + 5
>>> diff(f)
6⋅x + 4 
</pre>



<p>As you could see, in just one single line of code we managed to calculate the derivative of the function. In this case, it could be even possible to calculate the second derivative of “f” (it’s more correct to say that in this case the second derivative is not equal to zero), since it presents a second order term (x<sup>2</sup>). </p>



<p>To calculate the second or higher order derivatives of functions with <em>Sympy, </em>it is just sufficient to specify, after the function name, the variable with respect to which we want to make the derivation and the number of times we want to perform the differentiation (i.e. calculating the derivatives). In the following code lines, we calculate the second derivative of “f”, i.e. we differentiate the function twice.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> f
     2
3⋅x  + 4⋅x + 5
>>> diff(f, x, 2)
6
</pre>



<p>Also in this case, <em>Sympy </em>made the task awkwardly easy and immediate!</p>



<p>When we are dealing with multi-variable functions, we may be interested in calculating their partial derivatives; to do that, it is sufficient to specify the variable with respect to which we want to differentiate the function. In the following example, the function “g” is a three-variable function (x, y, z); we hence show how to calculate the partial derivatives with respect to each of three variables.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> g = 2*x + 4*y**2 - x*z
>>> diff(g, x)
2 - z
>>> diff(g, y)
8⋅y
>>> diff(g, z)
-x
</pre>



<h2 class="wp-block-heading">Integrals</h2>



<p>Integrating is the opposite operation compared to differentiating. From a graphical point of view, integrating a function means calculating the area between the function and the x-axis, but of course, the potential of <strong><em>Integral Calculus</em></strong> is not limited to just the areas beneath graphs.</p>



<p>In this section we will see firstly how to express an integral of a function in the terminal; as you will see, <em>Sympy </em>allows for a better representation of the function within the terminal. </p>



<p>To this purpose, we still use the “f” function defined at the beginning (you can find it also in the first lines of this code section) and we just define its integral, between the points -2 and 2. To do that, we exploit the function <em>Integral() </em>and pass as input parameters the function, the variable for which we want to integrate, followed by the lower and upper boundaries (these three latter parameters have to be put within parentheses).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> f
   2
3⋅x  + 4⋅x + 5
>>> Integral(f, (x, -2, 2))
  2
 ⌠
 ⎮       2                  
 ⎮  3⋅x  + 4⋅x + 5 dx
 ⌡
-2
</pre>



<p>At this stage, we have just expressed the integral that we want to solve, using the mathematical notation. However, what really interests us is how to actually solve the integral. To solve the integral, we use a function called <em>integrate(); </em>the input parameters are still the same; if you just want to solve the integral symbolically, you do not have to specify the integration limits. In the following code lines, we first solve the integral symbolically and then numerically by entering all the parameters already used with the function <em>Integral().</em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> integrate(f)
  3        2
x  + 2⋅x  + 5⋅x
>>> integrate(f, (x, -2, 2))
36
</pre>



<p>As you can see, thanks to the <em>integrate() </em>function, it was possible to solve the integral both symbolically and numerically in a very immediate way. With a similar approach, it is also possible to solve double or triple integrals; we just have to specify the boundaries for each variable, in the same way we did for the x variable in the example above; in the next code lines, we calculate the double integral of the function “g”.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> g = x**2 + 5*y
>>> integrate(g, (x, -2, 2), (y, 3, 5))
512/3
</pre>



<p>If we wanted to solve the integral symbolically with respect to just one of the two variables, it would have been sufficient to give as input that variable, right after the name of the function to integrate (“g” in this case).</p>



<h2 class="wp-block-heading">Limits</h2>



<p>In <a href="https://blog.finxter.com/daily-python-puzzle-basic-math-operations/" target="_blank" rel="noreferrer noopener" title="Basic Math Operations in Python: Four Ops in One Line">math</a>, limits are used to evaluate a function when it approaches “critical” points in which it could diverge or converge to a specific values, being them a finite number or  ± infinity. To calculate the limits of a mathematical function, we use the <em>Sympy </em>function <em>limit(); </em>it takes as input the function of interest, the variable to which the limit is referred to and the point in which we want to compute the limit, i.e. the point the independent variable “is approaching”. In the following example we evaluate the limit of the function <em>sin(x)/x</em> when x is approaching zero.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> limit(sin(x)/x, x, 0)
1
</pre>



<p>In some cases, the limits may assume different values whether the independent variable is approaching the critical point from higher or lower values; an example is the limit of the function <em>1/x</em>, evaluated in the proximity of zero; as you will see, the result is different if we approach to zero from higher or lower numbers. To specify the direction from which we want to “approach” the critical point, we add another input parameter, that is “-“ or “+”, indicating that we are approaching that critical point from lower or higher values, respectively.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> limit(1/x, x, 0, '-')
-∞
>>> limit(1/x, x, 0, '+')
∞
</pre>



<p>As predicted, the result of the limit in the two cases varies from –∞ to +∞.</p>



<h2 class="wp-block-heading">Plotting functions</h2>



<p>In this last section, we will explore another really useful feature of <em>Sympy, </em>that is the possibility to plot and hence display functions by just typing their equations, directly in the terminal. To accomplish this task, we should have previously installed <em>Matplotlib</em> (strictly speaking, this is not mandatory, <em>Sympy </em>is also able to represent the entire plot by using dots and lines; however, the graphical output is not the best; I personally recommend installing and exploit matplotlib). In the following examples, we will see just some of the most significant functions; however, keep in mind that there are lots of other different possibilities and options. </p>



<p>If you are interested in them, have a look at the official documentation here: <a href="https://docs.sympy.org/latest/modules/plotting.html" target="_blank" rel="noreferrer noopener">https://docs.sympy.org/latest/modules/plotting.html</a> </p>



<p>We start by looking at how to plot a single function; we firstly assign the plot to the variable “p1”; to plot the function, we use the function <em>plot(), </em>entering, as input parameters, the function (expressed explicitly) and the boundaries of the independent variable (this is not mandatory, if we do not specify any boundaries, the function will be displayed from -5 to +5).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> p1 = plot(3*x + 4, (x, -3, 3))</pre>



<p>At this point, we should be able to see in a separate <a href="https://blog.finxter.com/best-matplotlib-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="Best Matplotlib Cheat Sheet">matplotlib </a>window, the plot of our function; Figure 1 reports the outcome of the example.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="398" height="298" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-5.png" alt="" class="wp-image-22608" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-5.png 398w, https://blog.finxter.com/wp-content/uploads/2021/02/image-5-300x225.png 300w, https://blog.finxter.com/wp-content/uploads/2021/02/image-5-150x112.png 150w" sizes="auto, (max-width: 398px) 100vw, 398px" /></figure></div>



<p><strong><em>Figure 1: </em></strong>Plot of the function f(x) = 3x + 4, calculated for values of x from -3 to +3.</p>



<p>It is also possible to plot multiple graphs in the same plot, each of them with its own boundaries; to do that, we just have to exploit the function <em>extend(). </em>In the following code lines, we define a second plot, “p2”, we choose to not show it by specifying in the option “show=False” and through the <em>extend() </em>function, we add it to the initial plot, p1. We finally show p1. The final outcome is displayed in Figure 2.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> p2 = plot(x**2, (x, 3, 7), show=False)
>>> p1.extend(p2)
>>> p1.show()
</pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="396" height="297" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-3.png" alt="" class="wp-image-22606" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-3.png 396w, https://blog.finxter.com/wp-content/uploads/2021/02/image-3-300x225.png 300w, https://blog.finxter.com/wp-content/uploads/2021/02/image-3-150x113.png 150w" sizes="auto, (max-width: 396px) 100vw, 396px" /></figure></div>



<p><strong><em>Figure 2: </em></strong>The plot “p2” (defined from x=3 to x=7) has been added and displayed together with the initial one (p1).</p>



<p>Another interesting feature of <em>Sympy </em>is the possibility of plotting parametric functions like circumferences. To do that, we can exploit the function <em>plot_parametric(), </em>its input parameters are the “x” and “y” coordinates of the points defining the parametric curve, the parametric variable and its boundaries. The following code lines show how to plot a circumference centered at the origin of the axes, with its independent variable varying from -7 to 7. Figure 3 displays the matplotlib window with the plot hence generated.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> plot_parametric((cos(x), sin(x)), (x, -7, 7))</pre>



<p></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="309" height="232" src="https://blog.finxter.com/wp-content/uploads/2021/02/image-1.png" alt="" class="wp-image-22604" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image-1.png 309w, https://blog.finxter.com/wp-content/uploads/2021/02/image-1-300x225.png 300w, https://blog.finxter.com/wp-content/uploads/2021/02/image-1-150x113.png 150w" sizes="auto, (max-width: 309px) 100vw, 309px" /></figure></div>



<p><strong><em>Figure 3: </em></strong>Parametric representation of a circumference centered at the origin of the x and y axes.</p>



<p>The last function that we will explore allows you to plot functions giving as input parameter the equation in the implicit form. This feature could be really useful when dealing with really complex and long functions, for which is often difficult to obtain the explicit version (i.e. the one in which one variable is expressed as a function of all the others). To solve this task, the appropriate function is <em>plot_implicit(); </em>the input parameters are the implicit function (i.e. the one that displays both the variables in its equation) and the boundaries for each of the variables. In the following code lines, we plot a parabolic function, giving as input its implicit equation and changing the boundaries for both the x and the y coordinates. The final result is then shown in Figure 4.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> plot_implicit(x**2 + 2*y, (x, -2, 2), (y, -3, 3))</pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="346" height="259" src="https://blog.finxter.com/wp-content/uploads/2021/02/image.png" alt="" class="wp-image-22603" srcset="https://blog.finxter.com/wp-content/uploads/2021/02/image.png 346w, https://blog.finxter.com/wp-content/uploads/2021/02/image-300x225.png 300w, https://blog.finxter.com/wp-content/uploads/2021/02/image-150x112.png 150w" sizes="auto, (max-width: 346px) 100vw, 346px" /></figure></div>



<p><strong><em>Figure 4: </em></strong>Plot of a parabolic function obtained by passing as input parameter its equation in the implicit form.</p>



<h2 class="wp-block-heading">Conclusions</h2>



<p>This article showed how to use <em>Sympy </em>for solving mathematical tasks like derivatives, integrals and limits. In the final part, <em>Sympy </em>was used to obtain plots of the functions directly from the terminal. All the code that was shown in the different sections has been typed into the terminal; however, the same results can be obtained by writing the same functions within the script. This was just a very brief introduction to the amazing capacity of&nbsp; the <em>Sympy </em>library, I strongly suggest you to check the official documentation page (<a href="https://www.sympy.org/en/index.html">https://www.sympy.org/en/index.html</a> ), where you will find a plethora of other cool functions and options that could immediately offer an easy solution to most of your math problems.</p>
<p>The post <a href="https://blog.finxter.com/symbolic-math-with-sympy-advanced-functions-and-plots/">Symbolic Math with SymPy: Advanced Functions and Plots</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-04-11 08:21:57 by W3 Total Cache
-->