Matplotlib – Fill Spiral

Matplotlib – Fill Spiral ”; Previous Next In general definition, a spiral is a geometric curve that emanates from a central point and moves farther away as it revolves around that point. Spirals exhibit a whorled pattern and come in various forms, including Archimedean spirals, and logarithmic spirals. See the below image for reference − On the other hand, a Fill Spiral refers to the visual representation of a spiral curve in which the space enclosed by the spiral is filled with a color or pattern. In this tutorial, we”ll see two different ways of creating and filling spirals using Matplotlib. the process involves defining the mathematical equations that represent the spiral and then using a function like pyplot.fill() to color the region enclosed by the spiral. Creating a Basic Fill Spiral A basic fill spiral can be defined using parametric equations in polar coordinates. The pyplot.fill() function is tthen used to fill the region enclosed by the spiral with a color. Example Here is an example that creates the basic fill spiral using the pyplot.fill() and np.concatenate() functions. import matplotlib.pyplot as plt import numpy as np # Define parameters theta = np.radians(np.linspace(0,360*5,1000)) a = 1 b = 0.2 fig, axes = plt.subplots(figsize=(7, 4)) # Create a spiral for dt in np.arange(0, 2 * np.pi, np.pi / 2.0): x = a * np.cos(theta + dt) * np.exp(b * theta) y = a * np.sin(theta + dt) * np.exp(b * theta) dt = dt + np.pi / 4.0 x2 = a * np.cos(theta + dt) * np.exp(b * theta) y2 = a * np.sin(theta + dt) * np.exp(b * theta) # Concatenate points for filling xf = np.concatenate((x, x2[::-1])) yf = np.concatenate((y, y2[::-1])) # Fill the spiral plt.fill(xf, yf) # Display the plot plt.show() Output On executing the above code we will get the following output − Creating the Logarithmic Fill Spiral A logarithmic spiral is a specific type of spiral where the radius grows exponentially with the angle. Example The example constructs the logarithmic spiral in pieces, combining segments with different parameters. import matplotlib.pyplot as plt import numpy as np # Define parameters for the logarithmic spiral a = 2 b = 0.2 # Generate theta and radius values for different pieces theta1 = np.linspace(0, np.pi * 3.0, 1000, endpoint=True) r1 = np.exp(b * theta1) * a theta2 = np.linspace(np.pi, np.pi * 4.0, 1000, endpoint=True) r2 = np.exp(b * theta1) * a theta3 = np.linspace(np.pi, 0, 1000) r3 = r1[-1] * np.ones_like(theta3) theta4 = np.linspace(np.pi, 2 * np.pi, 1000) r4 = a * np.ones_like(theta4) theta5 = np.linspace(np.pi, 2 * np.pi, 1000) r5 = r1[-1] * np.ones_like(theta5) theta6 = np.linspace(0, np.pi, 1000) r6 = a * np.ones_like(theta6) # Concatenate pieces for filling theta_final_red = np.concatenate([theta1, theta3, np.flip(theta2), theta4]) radius_red = np.concatenate([r1, r3, np.flip(r2), r4]) theta_final_blue = np.concatenate([theta1, theta5, np.flip(theta2), theta6]) radius_blue = np.concatenate([r1, r5, np.flip(r2), r6]) # Plot the filled spirals fig = plt.figure(figsize=(7,4)) ax = fig.add_subplot(111, projection=”polar”) ax.set_rmax(r1[-1]) ax.fill(theta_final_red, radius_red, “g”) ax.fill(theta_final_blue, radius_blue, “r”) # Plot the individual pieces ax.plot(theta1, r1) ax.plot(theta2, r2) # Black inner circle theta_inner = np.linspace(0, np.pi * 2.0, 1000, endpoint=True) r_inner = [a] * len(theta_inner) ax.fill(theta_inner, r_inner, c=”black”) ax.axis(False) ax.grid(False) # Display the plot plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Print Stdout

Matplotlib – Print Stdout ”; Previous Next Print − usually refers to displaying something, like text or numbers, on a screen or on paper. stdout − stands for “standard output.” It is a way for a program to send information (like text or data) out of itself. When a program “prints” something to stdout, it is essentially saying, “Here”s some information I want to show or share”. So, when you hear “print stdout” together, it means a program is sending some information to be displayed in a standard way, usually on your screen. It is a basic method for programs to communicate with users or other parts of the computer system. Print Stdout in Matplotlib The term “print stdout” is not specific to Matplotlib. It generally refers to printing output to the standard output stream in Python, which is the console or terminal where you run your Python code. In Matplotlib, if you want to print output to the console, you can use Python”s built-in print() function. For example, you can print information about your plot, data, or any messages or debugging information. Print Text on Plot Printing text on a plot in Matplotlib allows you to add labels, titles, annotations, or any other textual information to enhance the understanding of your data visualization. You can place text at specific locations on the plot to provide explanations, highlight important points, or label different elements. Example In the following example, we plot a line and add the text “Hello, Matplotlib!” to the plot using the text() function. We position the text at coordinates (2, 5) with a specified “fontsize” and “color” − import matplotlib.pyplot as plt # Creating a simple plot plt.plot([1, 2, 3], [4, 5, 6]) # Adding text annotation to the plot plt.text(2, 5, ”Hello, Matplotlib!”, fontsize=12, color=”red”) # Displaying the plot plt.show() Output Following is the output of the above code − Print Text on Polar Plot Printing text on a polar plot in Matplotlib allows you to add labels, annotations, or any other textual information to enhance the understanding of your polar visualization. Just like in Cartesian plots, you can place text at specific locations on the polar plot to provide explanations, highlight important points, or label different elements. Example In here, we create a polar plot and add the text “Polar Plot” to the plot using the text() function. We position the text at an angle of “π/2” (90 degrees) and a radius of “0.5” from the origin, with a specified fontsize, color, and horizontal alignment − import matplotlib.pyplot as plt import numpy as np # Creating a polar plot theta = np.linspace(0, 2*np.pi, 100) r = np.sin(3*theta) plt.polar(theta, r) # Adding text annotation to the polar plot plt.text(np.pi/2, 0.5, ”Polar Plot”, fontsize=12, color=”blue”, ha=”center”) # Displaying the polar plot plt.show() Output On executing the above code we will get the following output − Print Text with Rotation Printing text with rotation in Matplotlib allows you to display text at an angle, which can be useful for labeling elements with slanted or diagonal orientations, or for adding stylistic effects to your plots. Example Now, we plot a line and add rotated text to the plot using the “rotation” parameter of the text() function. We position the text “Rotated Text” at coordinates (2, 5) with a specified fontsize, color, and rotation angle of “45” degrees − import matplotlib.pyplot as plt # Creating a simple plot plt.plot([1, 2, 3], [4, 5, 6]) # Adding rotated text annotation to the plot plt.text(2, 5, ”Rotated Text”, fontsize=12, color=”purple”, rotation=45) # Displaying the plot plt.show() Output After executing the above code, we get the following output − Print Text with Box Printing text with a box in Matplotlib refers to adding textual annotations to a plot with a surrounding box, highlighting important information. These annotations can include labels, titles, or descriptions, and are enclosed within a rectangular or square-shaped box to draw attention to them. To print text with a box around it in Matplotlib, you can use the “bbox” parameter of the text() function. This parameter allows you to specify the properties of the box, such as its color, transparency, and border width. Example In the following example, we plot a line and add boxed text to the plot using the text() function. We position the text “Boxed Text” at coordinates (2, 5) with a specified fontsize, color, and a box with rounded corners, light yellow face color, and orange edge color − import matplotlib.pyplot as plt # Creating a simple plot plt.plot([1, 2, 3], [4, 5, 6]) # Adding boxed text annotation to the plot plt.text(2, 5, ”Boxed Text”, fontsize=12, color=”orange”, bbox=dict(facecolor=”lightyellow”, edgecolor=”orange”, boxstyle=”round,pad=0.5”)) # Displaying the plot plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Figure Class

Matplotlib – Figure Class ”; Previous Next In Matplotlib, a Figure is a top-level container that holds all the elements of a plot or visualization. It is an overall window or canvas that contains various components like axes, labels, titles, legends, colorbars, and other elements. See the below image for reference − In the above image, the green region represents the figure and the white region is the axes area. Figure Class in Matplotlb The Figure() class in Matplotlib is a top-level artist that acts as the primary container for all plot elements. It holds everything together, including subplots, axes, titles, legends, and other artistic elements. This class is available in the matplotlib.figure module with several customization options, in addition to the Figure() class, the module also contains classes related to creating and managing figures. Creating a Figure A Figure instance is typically created using pyplot methods such as figure, subplots, and subplot_mosaic. These methods return both a Figure instance and a set of Axes, providing a convenient way to create and work with visualizations. Example Here is an example that uses the pyplot.figure() method to create a figure. import matplotlib.pyplot as plt import numpy as np # Creating the Figure instance fig = plt.figure(figsize=[7, 3], facecolor=”lightgreen”, layout=”constrained”) # Adding a title to the Figure fig.suptitle(”Figure”) # Adding a subplot (Axes) to the Figure ax = fig.add_subplot() # Setting a title for the subplot ax.set_title(”Axes”, loc=”left”, fontstyle=”oblique”, fontsize=”medium”) # Showing the plot plt.show() Output On executing the above code we will get the following output − Example This example demonstrates how to create multiple figures separately within a single script in Matplotlib. from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7, 3.50] plt.rcParams[“figure.autolayout”] = True # Create Figure 1 fig1 = plt.figure(“Figure 1″) plt.plot([1, 3, 7, 3, 1], c=”red”, lw=2) plt.title(“Figure 1”) # Create Figure 2 fig2 = plt.figure(“Figure 2″) plt.plot([1, 3, 7, 3, 1], c=”green”, lw=5) plt.title(“Figure 2″) # Display both figures plt.show() Output On executing the above code you will get the following output −   Creating a Figure with Grids of Subplots When creating figures, various options can be customized, including subplots, size, resolution, colors, and layout. The Figure class attributes such as figsize, dpi, facecolor, edgecolor, linewidth, and layout play crucial roles in shaping the appearance of your visualizations. Example Here is an example that uses the pyplot.subplots() method to create a 2×2 grid of subplots with multiple various customization options. import matplotlib.pyplot as plt import numpy as np # Create a 2×2 grid of subplots with various customization options fig, axs = plt.subplots(2, 2, figsize=(7, 4), facecolor=”lightgreen”, layout=”constrained”) # Super title for the entire figure fig.suptitle(”2×2 Grid of Subplots”, fontsize=”x-large”) # Display the Figure plt.show() Output On executing the above code we will get the following output − Example Here is another example that creates a more complex layout using the plt.subplot_mosaic() method. import matplotlib.pyplot as plt # Create a more complex layout using plt.subplot_mosaic() fig, axs = plt.subplot_mosaic([[”A”, ”right”], [”B”, ”right”]], facecolor=”lightgreen”, layout=”constrained”) # Add text to each subplot for ax_name, ax in axs.items(): ax.text(0.5, 0.5, ax_name, ha=”center”, va=”center”, fontsize=”large”, fontweight=”bold”, color=”blue”) # Super title for the entire figure fig.suptitle(”Complex Layout using subplot_mosaic()”, fontsize=”x-large”) # Display the Figure plt.show() Output On executing the above code we will get the following output − Saving a Figure After completing a visualization, saving Figures to disk is simple using the savefig() method. This method allows you to specify the file format (e.g., PNG, PDF) and customize options such as resolution and bounding box. Example Let’s see a simple example to save the Figure object. import matplotlib.pyplot as plt # Create a 2×2 grid of subplots with various customization options fig, axs = plt.subplots(2, 2, figsize=(7, 4), facecolor=”lightgreen”, layout=”constrained”) # Super title for the entire figure fig.suptitle(”2×2 Grid of Subplots”, fontsize=”x-large”) # Super title for the entire figure fig.suptitle(”Saving a Figure”, fontsize=”x-large”) # Display the Figure plt.show() # Save the Figure object to a file fig.savefig(”Saved Figure.png”, dpi=300) Output On executing the above program, the following figure will be saved in your working direcory − Print Page Previous Next Advertisements ”;

Matplotlib – Tick Locators

Matplotlib – Tick Locators ”; Previous Next In general graphs and plottings, ticks play a crucial role in representing the scale of x and y-axes through small lines, offering a clear indication of the associated values. Tick locators, on the other hand, define the positions of these ticks along the axis, offering a visual representation of the scale. The below image represents the major and minor ticks on a graph − Tick Locators in Matplotlib Matplotlib provides a mechanism for controlling the positioning of ticks on axes through its tick locators. The matplotlib.ticker module contains classes for configuring tick locating and formatting. These classes include generic tick locators, Formatters, and domain-specific custom ones. While locators are unaware of major or minor ticks, they are used by the Axis class to support major and minor tick locating and formatting. Different Tick Locators The matplotlib provides different tick locator within its ticker module, allowing users to customize the tick positions on axes. Some of the Tick Locators include − AutoLocator MaxNLocator LinearLocator LogLocator MultipleLocator FixedLocator IndexLocator NullLocator SymmetricalLogLocator AsinhLocator LogitLocator AutoMinorLocator Defining Custom Locators Basic Setup Before diving into specific tick locators, let”s establish a common setup function to draw the plot with ticks. import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker def draw_ticks(ax, title): # it shows the bottom spine only ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines[[”left”, ”right”, ”top”]].set_visible(False) ax.xaxis.set_ticks_position(”bottom”) ax.tick_params(which=”major”, width=1.00, length=5) ax.tick_params(which=”minor”, width=0.75, length=2.5) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.text(0.0, 0.2, title, transform=ax.transAxes, fontsize=14, fontname=”Monospace”, color=”tab:blue”) Now, let”s explore the working of each tick locator. Auto Locator The AutoLocator and AutoMinorLocator are used for automatically determining the positions of major and minor ticks on an axis, respectively. Example This example demonstrates how to use the AutoLocator and AutoMinorLocator to automatically handle the positioning of major and minor ticks on an axis. # Auto Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”AutoLocator() and AutoMinorLocator()”) ax.xaxis.set_major_locator(ticker.AutoLocator()) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.set_title(”Auto Locator and Auto Minor Locator”) plt.show() Output Null Locator The NullLocator places no ticks on the axis. Example Let’s see the following example for working of the NullLocator. # Null Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”NullLocator()”) ax.xaxis.set_major_locator(ticker.NullLocator()) ax.xaxis.set_minor_locator(ticker.NullLocator()) ax.set_title(”Null Locator (No ticks)”) plt.show() Output Multiple Locator The MultipleLocator() class allows ticks to be positioned at multiples of a specified base, supporting both integer and float values. Example The following example demonstrates how to use the MultipleLocator() class. # Multiple Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”MultipleLocator(0.5)”) ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax.set_title(”Multiple Locator”) plt.show() Output Fixed Locator The FixedLocator() places ticks at specified fixed locations. Example Here is an example of using the FixedLocator() class. # Fixed Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”FixedLocator([0, 1, 3, 5])”) ax.xaxis.set_major_locator(ticker.FixedLocator([0, 1, 3, 5])) ax.xaxis.set_minor_locator(ticker.FixedLocator(np.linspace(0.2, 0.8, 4))) ax.set_title(”Fixed Locator”) plt.show() Output Linear Locator The LinearLocator spaces ticks evenly between specified minimum and maximum values. Example Here is an example that applies the Linear Locator to the major and minor ticks of an axes. # Linear Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”LinearLocator(numticks=3)”) ax.xaxis.set_major_locator(ticker.LinearLocator(3)) ax.xaxis.set_minor_locator(ticker.LinearLocator(10)) ax.set_title(”Linear Locator”) plt.show() Output Index Locator This locator is suitable for index plots, where x = range(len(y)). Example Here is an example that uses the index loctator (ticker.IndexLocator() class). # Index Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”IndexLocator(base=0.5, offset=0.25)”) ax.plot([0]*5, color=”white”) ax.xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25)) ax.set_title(”Index Locator”) plt.show() Output MaxN Locator The MaxNLocator finds up to a maximum number of intervals with ticks at nice locations. Example Here is an example of using the MaxNLocator() class for both major and minor ticks. # MaxN Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”MaxNLocator(n=4)”) ax.xaxis.set_major_locator(ticker.MaxNLocator(4)) ax.xaxis.set_minor_locator(ticker.MaxNLocator(40)) ax.set_title(”MaxN Locator”) plt.show() Output Log Locator The LogLocator is used for spacing ticks logarithmically from min to max. Example Let”s see an example of using the Log Locator. It shows the minor tick labels on a log-scale. # Log Locator fig, ax = plt.subplots(1,1,figsize=(7,1.5), facecolor=”#eaffff”) plt.subplots_adjust(bottom=0.3, top=0.6, wspace=0.2, hspace=0.4) draw_ticks(ax, title=”LogLocator(base=10, numticks=15)”) ax.set_xlim(10**3, 10**10) ax.set_xscale(”log”) ax.xaxis.set_major_locator(ticker.LogLocator(base=10, numticks=15)) ax.set_title(”Log Locator”) plt.show() Output Print Page Previous Next Advertisements ”;

Matplotlib – Dateticks

Matplotlib – Dateticks ”; Previous Next In general plotting, dateticks refer to the labels of the tick lines or markers on the axes of a plot with dates or times, replacing the default numeric values. This feature is especially useful when dealing with time series data. The image below illustrates Dateticks on a plot − Dateticks in Matplotlib Matplotlib provides powerful tools for plotting time-series data, allowing users to represent dates or times instead of the default numeric values on the tick lines or markers (dateticks). The library simplifies the process of working with dates by converting date instances into days since the default epoch (1970-01-01T00:00:00). This conversion, along with tick locating and formatting, occurs in the background, making it transparent to the user. The matplotlib.dates module plays a key role in handling various date-related functionalities. This includes converting data to datetime objects, formatting dateticks labels, and setting the frequency of ticks. Basic Dateticks with DefaultFormatter Matplotlib sets the default tick locator and formatter for the axis, using the AutoDateLocator and AutoDateFormatter classes respectively. Example This example demonstrates the plotting of time-series data, here Matplotlib handles the date formatting automatically. import numpy as np import matplotlib.pylab as plt # Generate an array of dates times = np.arange(np.datetime64(”2023-01-02”), np.datetime64(”2024-02-03”), np.timedelta64(75, ”m”)) # Generate random data for y axis y = np.random.randn(len(times)) # Create subplots fig, ax = plt.subplots(figsize=(7,4), facecolor=”.9”) ax.plot(times, y) ax.set_xlabel(”Dataticks”,color=”xkcd:crimson”) ax.set_ylabel(”Random data”,color=”xkcd:black”) plt.show() Output On executing the above code we will get the following output − Customizing Dateticks with DateFormatter For manual customization of date formats, Matplotlib provides the DateFormatter module, which allows users to change the format of dateticks. Example This example demonstrates how to manually customize the format of Dateticks. import numpy as np import matplotlib.pylab as plt import matplotlib.dates as mdates # Generate an array of dates times = np.arange(np.datetime64(”2023-01-02”), np.datetime64(”2024-02-03”), np.timedelta64(75, ”m”)) # Generate random data for y axis y = np.random.randn(len(times)) # Create subplots fig, ax = plt.subplots(figsize=(7,5)) ax.plot(times, y) ax.set_title(”Customizing Dateticks using DateFormatter”) ax.xaxis.set_major_formatter(mdates.DateFormatter(”%Y-%b”)) # Rotates and right-aligns the x labels so they don”t overlap each other. for label in ax.get_xticklabels(which=”major”): label.set(rotation=30, horizontalalignment=”right”) plt.show() Output On executing the above code we will get the following output − Advanced Formatting with ConciseDateFormatter The ConciseDateFormatter class in Matplotlib simplifies and enhances the appearance of dateticks. This formatter is designed to optimize the choice of strings for tick labels and minimizes their length, which often removes the need to rotate the labels. Example This example uses the ConciseDateFormatter and AutoDateLocator classes to set the best tick limits and date formats for the plotting. import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np # Define a starting date base_date = datetime.datetime(2023, 12, 31) # Generate an array of dates with a time delta of 2 hours num_hours = 732 dates = np.array([base_date + datetime.timedelta(hours=(2 * i)) for i in range(num_hours)]) date_length = len(dates) # Generate random data for the y-axis np.random.seed(1967801) y_axis = np.cumsum(np.random.randn(date_length)) # Define different date ranges date_ranges = [ (np.datetime64(”2024-01”), np.datetime64(”2024-03”)), (np.datetime64(”2023-12-31”), np.datetime64(”2024-01-31”)), (np.datetime64(”2023-12-31 23:59”), np.datetime64(”2024-01-01 13:20”)) ] # Create subplots for each date range figure, axes = plt.subplots(3, 1, constrained_layout=True, figsize=(6, 6)) for nn, ax in enumerate(axes): # AutoDateLocator and ConciseDateFormatter for date formatting locator = mdates.AutoDateLocator(minticks=3, maxticks=7) formatter = mdates.ConciseDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) # Plot the random data within the specified date range ax.plot(dates, y_axis) ax.set_xlim(date_ranges[nn]) axes[0].set_title(”Concise Date Formatter”) # Show the plot plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Axes Class

Matplotlib – Axes Class ”; Previous Next In the context of Matplotlib, axes does not refer to the plural form of an axis. Instead, it represents the entire plotting area on a figure or canvas. Which includes the x-axis, y-axis, plotting data, ticks, ticks labels, and more. Refer to the image below − Consider the figure where two Axes objects are created using the ax = fig.subplots() method. The first axes display exponential data, while the second axes show a sine wave. Each Axes (subplot) has its own set of labels, ticks, and legends, providing a distinct representation within the same figure. Axes class in matplotlib The Axes() class serves as the gateway to creating data visualizations. Once an Axes object is instantiated on a figure, a variety of methods become available to add and manipulate data within that plotting area. This class is part of the matplotlib.axes module, providing fundamental functionalities to work with the Matplotlib object-oriented programming (OOP) interface. Most of the essential plotting methods are defined on the Axes class, making it a central component for customizing and enhancing visualizations. Creating an Axes Creating an Axes object is typically the first step in Matplotlib plotting. This can be done through methods on Figure object like Figure.subplots(), Figure.add_axes(), or via the pyplot interface function, pyplot.subplots(). These methods provides the creation of one or more Axes objects in a figure. Example The following example uses the pyplot.subplot() method to creat two axes on a figure. The subplots() method is useful for generating the axes instance. import matplotlib.pyplot as plt import numpy as np # Creating a 1×2 subplot layout fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4), layout=”constrained”) # Adding labels to each subplot axes1.annotate(”axes1”, (0.5, 0.5),transform=axes1.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) axes2.annotate(”axes2”, (0.5, 0.5),transform=axes2.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) fig.suptitle(”Creating Two Axes on a Figure”) # Displaying the plot plt.show() Output On executing the above code we will get the following output − Changing an Axes properties To set the properties of an axes, you have to access the axes object, after that you can use various `set_*` methods to modify its properties. Example import matplotlib.pyplot as plt import numpy as np # Creating a 1×2 subplot layout fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4), constrained_layout=True) # Changing the properties of the first axes axes1.set_xlabel(“X-axis”) # Set label for X-axis axes1.set_ylabel(“Y-axis”) # Set label for Y-axis axes1.set_facecolor(”lightgreen”) # Setting background color axes1.annotate(”axes1”, (0.5, 0.5), transform=axes1.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) axes2.set_title(”Second axes”) axes2.annotate(”axes2”, (0.5, 0.5), transform=axes2.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) # Adding a title to the figure fig.suptitle(”Changing Axes Properties”) # Displaying the plot plt.show() Output On executing the above code you will get the following output − Plotting on an Axes This class offers several high-level plotting methods to create different plot on axes. Example Here is an example uses the Axes.plot() method to create a line plot representing the sin(x). import matplotlib.pyplot as plt import numpy as np # Sample Data x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x**2) # Create subplots fig, axs = plt.subplots(figsize=(7,4)) # Draw the plot axs.plot(x, y) # Show the plot plt.show() Output On executing the above code we will get the following output − Customizing the axes Data The Axes object contains most of the figure elements such as Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. These elements can be customized by adding labels, titles, legends, and annotations to the Axes enhances the clarity of visualizations. Example Here is a simple example that adds the labels, titles, legends to an Axes. import matplotlib.pyplot as plt import numpy as np # Sample Data x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x**2) # Create subplots fig, axs = plt.subplots(figsize=(7,4)) # Draw the plot axs.plot(x, y, label=”Sin(x)”) # Add titles axs.set_title(”Sin Plot”) # Add X and Y labels axs.set_xlabel(”X-axis”) axs.set_ylabel(”Y-axis”) # Add legend axs.legend() # Show the plot plt.show() Output On executing the above code we will get the following output − Clearing the Axes To clear the contents of an axes, you can use the axes.cla() or axes.clear() method. Example Here is an example that show how you can clear the first axes in a subplot. import matplotlib.pyplot as plt import numpy as np # Sample data x = np.linspace(-1, 1, 10) y = np.exp(x) # Creating subplots fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4), constrained_layout=True) # Plotting on the first axes axes1.plot(x, y, c=”red”) axes1.set_xlabel(“X-axis”) # Set label for X-axis axes1.set_ylabel(“Y-axis”) # Set label for Y-axis axes1.set_facecolor(”lightgreen”) # Setting background color axes1.annotate(”axes1”, (0.5, 0.5), transform=axes1.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) # Adding a title to the second axes axes2.set_title(”Second axes”) axes2.annotate(”axes2”, (0.5, 0.5), transform=axes2.transAxes, ha=”center”, va=”center”, fontsize=18, color=”darkgrey”) # Clearing the first axes axes1.cla() # Adding a title to the figure fig.suptitle(”Clearing the Axes”) # Displaying the plot plt.show() Output On executing the above code you will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – MRI with EEG

Matplotlib – MRI with EEG ”; Previous Next MRI with EEG refers to a medical imaging technique that combines two different methods to study the brain: Magnetic Resonance Imaging (MRI) and Electroencephalography (EEG). MRI (Magnetic Resonance Imaging) − MRI uses strong magnetic fields and radio waves to create detailed images of the inside of the body, including the brain. It helps doctors see the structure and anatomy of the brain, detecting abnormalities like tumors, injuries, or other conditions. EEG (Electroencephalography) − EEG measures the electrical activity in the brain by placing electrodes on the scalp. It records the patterns of electrical impulses produced by brain cells, called neurons. When MRI and EEG are combined, it allows doctors and researchers to study both the structure and activity of the brain simultaneously. MRI with EEG in Matplotlib Matplotlib allows you to create visualizations that integrate MRI images with EEG data, enabling the exploration and analysis of brain function and connectivity. In Matplotlib, there isn”t a specific function for creating MRI with EEG visualizations. Instead, you need to use a combination of Matplotlib”s plotting functions to overlay EEG data onto MRI images. This involves loading and processing the MRI and EEG data separately, then using Matplotlib to display them together in a single plot. You can use functions like imshow() to display the MRI image and plot() or scatter() to overlay the EEG data onto the MRI image. Additionally, you can adjust the appearance and layout of the plot using various customization options provided by Matplotlib. Displaying MRI Slice In Matplotlib, displaying an MRI slice involves visualizing a single two-dimensional cross-section of a three-dimensional MRI volume. This allows you to examine the internal structures of the body captured by the MRI scanner. You can load and display the MRI slice as an image within a plot using Matplotlib”s plotting functions, such as imshow(). Example In the following example, we are generating synthetic MRI data using np.random.rand, creating a 3D array of random numbers representing MRI voxel intensities. We save this synthetic MRI data to a NIfTI file named ”sample_mri.nii.gz” using Nibabel”s nib.save. We then load the synthetic MRI data from the saved file using nib.load and display a single slice (slice index 50) of the MRI data using Matplotlib”s imshow() function− import matplotlib.pyplot as plt import nibabel as nib import numpy as np # Generating sample MRI data sample_data = np.random.rand(100, 100, 100) # Saving sample MRI data to a NIfTI file nib.save(nib.Nifti1Image(sample_data, np.eye(4)), ”sample_mri.nii.gz”) # Loading sample MRI data mri_img = nib.load(”sample_mri.nii.gz”) mri_data = mri_img.get_fdata() # Displaying a single MRI slice plt.imshow(mri_data[:, :, 50], cmap=”gray”) plt.title(”Sample MRI Slice”) plt.axis(”off”) plt.show() Output Following is the output of the above code − Plot EEG Signal Plotting an EEG signal in Matplotlib involves visualizing the electrical activity recorded from electrodes placed on the scalp. EEG signals represent the brain”s neural activity over time, capturing changes in electrical potentials associated with various brain states and activities. In Matplotlib, you can plot EEG data using functions like plot() to display the signal amplitude over time. EEG plots typically have time on the x-axis and voltage or signal amplitude on the y-axis, allowing researchers and clinicians to analyze brain activity patterns, detect abnormalities, and study cognitive processes. Example In here, we are generating synthetic EEG data and plotting the EEG signal over time using Matplotlib”s plot() function − import matplotlib.pyplot as plt import numpy as np # Generating sample EEG data # Sampling frequency (Hz) fs = 1000 # Time vector (10 seconds) t = np.arange(0, 10, 1/fs) # Sample EEG signal eeg_signal = np.sin(2 * np.pi * 10 * t) + 0.5 * np.random.randn(len(t)) # Plotting EEG signal plt.plot(t, eeg_signal) plt.title(”EEG Signal”) plt.xlabel(”Time (s)”) plt.ylabel(”Amplitude”) plt.show() Output On executing the above code we will get the following output − MRI Overlay with EEG Electrodes Overlaying EEG electrodes onto an MRI image in Matplotlib involves combining two different types of medical data for visualization. The MRI provides detailed anatomical information about the brain”s structures, while the EEG electrodes capture electrical signals from the brain”s surface. By overlaying EEG electrodes onto the MRI image, researchers and clinicians can correlate brain activity with specific brain regions. You can achieve this overlay in Matplotlib by plotting the MRI image using the imshow() function and then superimposing the EEG electrode positions using symbols or markers. Example The following example generates an MRI image and overlays EEG electrode positions on a single MRI slice using Matplotlib − import matplotlib.pyplot as plt import numpy as np # Generating synthetic MRI data mri_shape = (100, 100, 100) mri_data = np.random.rand(*mri_shape) # Generating sample EEG electrode positions (x, y coordinates) eeg_electrodes = np.array([[30, 40], [50, 60], [70, 80]]) # Displaying a single MRI slice plt.imshow(mri_data[:, :, 50], cmap=”gray”) # Overlaying EEG electrode positions plt.scatter(eeg_electrodes[:, 0], eeg_electrodes[:, 1], color=”red”, marker=”o”, label=”EEG Electrodes”) # Adding legend plt.legend() # Adding title and axis labels plt.title(”MRI Slice with EEG Electrodes”) plt.xlabel(”X”) plt.ylabel(”Y”) # Displaying plot plt.show() Output After executing the above code, we get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Mathematical Expressions

Matplotlib – Mathematical Expressions ”; Previous Next In general, mathematical expressions are combinations of symbols that obey specific rules within a given mathematical context. These symbols can represent numbers, variables, operations, functions, and more. The structure of mathematical expressions follows rules that determine the order of operations and other aspects of logical syntax. Following are a few examples of mathematical expressions − Mathematical Expressions in Matplotlib Matplotlib allows users to include mathematical expressions in text elements(text object) to enhance the visual representation of mathematical elements in plots and figures. The following image shows the inclusion of mathematical expressions in matplotlib plot − Mathtext in Matplotlib Matplotlib uses a module called Mathtext to render the math expressions in plots. It is a lightweight TeX expression parser and layout engine to render the math expressions in Matplotlib. Key Features of Mathtext Mathtext supports various features such as − Symbols Special characters Subscripts, Superscripts, and Standard Function Names Fractions and binomials Radicals Different fonts and more The Mathtext expressions should be enclosed in dollar signs (”$”) and can include various symbols and commands. The text objects like titles, lables, annotations, and figure text are the common places in Matplotlib where mathematical expressions are included. Basic Mathematical Text Basic mathematical text can include binary operation symbols like ‘+’, ‘-’, ‘*’,… to represent various mathematical operations between two elements. Example This example demonstrates the inclusion of binary operation symbols like +, − to denote addition, subtraction respectively. import matplotlib.pyplot as plt # Create a plot fig = plt.figure(figsize=(7, 4)) # Displaying basic mathematical text plt.text(.5, .5, r”$x^2 – 4x + 7$”, fontsize=16, ha=”center”) # Show the plot plt.show() Output On executing the above code we will get the following output − Radical, Greek Letters, and Delimiters Radicals, Greek letters, and delimiters are key components in mathematical expressions. A radical, denoted by the square root symbol(√), represents the root of a number or expression. Greek letters, such as α(alpha), β(beta), γ(gamma), and more are the symbols used to represente the standard mathematical notation. Delimiters, including parentheses, brackets, and braces, are used to group the expressions, while mainting the the proper order of operations in mathematical statements. Example Here is an example of including the mathmetical expression with radicals, greek latters and delimiters. import matplotlib.pyplot as plt # Create a figure fig = plt.figure(figsize=(7, 4)) # Add Greek Letters within the plots plt.text(0.25, 0.2, r”Greek Letters: $alpha, beta, gamma$”, fontsize=16) # Radicals plt.text(0.3, 0.5, r”Radical: $sqrt{2}$”, fontsize=16) # delimiters plt.text(0.2, 0.8, r”delimiters: $(a + b) left{c – dright}$”, fontsize=16) # Show the plot plt.show() Output On executing the above code we will get the following output − Fractions, Binomials, and Stacked Numbers Fractions are ratio of two numbers, written as one number over another, conveying the division of one quantity by another. Binomials involve expressions with two terms, often connected by addition or subtraction. In the context of binomial coefficients, binomials can represent combinations or choices within a set. Stacked numbers refer to the vertical alignment of numerical values, commonly seen in mathematical notations such as exponents or nested expressions. Example Here is an example of including the mathmetical expreassion with Fractions, Binomials, and Stacked Numbers. import matplotlib.pyplot as plt # Create a plot fig = plt.figure(figsize=(7, 4)) # Fractions, binomials, and stacked numbers plt.text(0.4, 0.7, r”$frac{3}{4} binom{3}{4} genfrac{}{}{0}{}{3}{4}$”, fontsize=16) plt.text(0.4, 0.3, r”$left(frac{5 – frac{1}{x}}{4}right)$”, fontsize=16) plt.show() Output The above example produces the following output − Subscripts, Superscripts and Standard Function Names In mathematical notation, subscripts and superscripts are used to denote indices or exponents, respectively. Whereas, Standard function names are commonly used mathematical functions such as sine, cosine, logarithm, and summation, often denoted by specific symbols or abbreviations. Example Here is the example of including the mathmetical expression with Subscripts, Superscripts and Standard Function Names. import matplotlib.pyplot as plt # Create a figure fig = plt.figure(figsize=(7, 4)) # Add mathmetical expression with Subscripts, Superscripts and Standard Function Names plt.text(0.3, 0.6, r”$sum_{i=0}^infty x_i quad sin(theta) quad log(e^x)$”, fontsize=16) # Subscripts and superscripts plt.text(0.5, 0.3, r”$log^a_i (x)$”, fontsize=16) # Show the plot plt.show() Output Here is the output of the above example − Example Here is another example that writes text in subscript in the axis labels and the legend. import numpy as np import matplotlib.pyplot as plt # Adjust figure size and autolayout plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True # Generate data x = np.linspace(1, 10, 1000) y = np.exp(x) # Plot data plt.plot(x, y, label=r”$e^x$”, color=”red”, linewidth=2) # Set axis labels plt.xlabel(“$X_{mathrm{axis}}$”) plt.ylabel(“$Y_{mathrm{axis}}$”) # Set legend plt.legend(loc=”upper left”) # Display plot plt.show() Output On executing the above code you will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Radian Ticks

Matplotlib – Radian Ticks ”; Previous Next A radian is a unit of angular measure used to express angles in mathematics and physics. Ticks, in the field of data visualization, refer to the small lines or marks indicating the scale of the axes. Radian Ticks in Matplotlib In the context of Matplotlib, radian ticks typically denote the ticks or markers on an axis that represent values in radians. When dealing with circular or angular data, it is common to use radian ticks on the axis to indicate specific angles. Setting radian ticks involves placing tick marks at specific intervals corresponding to certain radian values on the axis. Here is a reference image illustrating Radian ticks on a plot − In the image, you can observe that radian ticks represent the angles of the sine wave along the x-axis. Radian Ticks for the x axis Setting Radian Ticks for the x-axis involves using two key methods which are axes.set_xticks() and axes.set_xticklabels(). These methods are allowing you to specify the positions and labels of ticks on the x-axis, respectively. In addition to these methods, the FormatStrFormatter and MultipleLocator classes from the matplotlib.ticker module can be used to enhance the customization of tick positions and labels. Example 1 The following example demonstrates how to create a plot with custom radian ticks. import matplotlib.pyplot as plt import numpy as np # Create plot fig, ax = plt.subplots(figsize=(7, 4)) # Sample data theta = np.linspace(0, 2 * np.pi, 100) y = np.sin(theta) # Plotting the data plt.plot(theta, y) plt.title(”Sine Wave”) plt.xlabel(”Angle (radians)”) plt.ylabel(”Y-axis”) # Custom radian ticks and tick labels custom_ticks = [0, np.pi/2, np.pi, (3*np.pi)/2, 2*np.pi] custom_tick_labels = [”$0$”, ”$pi/2$”, ”$pi$”, ”$3pi/2$”, ”$2pi$”] ax.set_xticks(custom_ticks) ax.set_xticklabels(custom_tick_labels) plt.grid(axis=”x”) # Display the plot plt.show() Output On executing the above code we will get the following output − Example 2 This example uses the FormatStrFormatter and MultipleLocator classes from the matplotlib.ticker module to control the format and positions of ticks. import matplotlib.pyplot as plt import matplotlib.ticker as tck import numpy as np # Create Plot f,ax=plt.subplots(figsize=(7,4)) # Sample Data x=np.linspace(0, 2 * np.pi, 100) y=np.sin(x) # Plot the sine wave ax.plot(x/np.pi,y) # Customizing X-axis Ticks ax.xaxis.set_major_formatter(tck.FormatStrFormatter(”%g $pi$”)) ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0)) # Set the titles plt.title(”Sine Wave”) plt.xlabel(”Angle (radians)”) plt.ylabel(”Y-axis”) plt.grid() plt.show() Output On executing the above code we will get the following output − Radian Ticks for the y axis Similar to the x-axis, setting radian ticks for the y-axis can be done by using the ax.set_yticks() and ax.set_yticklabels() methods. These methods allow you to define the positions and labels of ticks on the y-axis. Additionally, the FormatStrFormatter and MultipleLocator classes from the matplotlib.ticker module can also used. Example This example demonstrates how to set customized radian ticks for the y-axis. using the FormatStrFormatter and MultipleLocator classes from the matplotlib.ticker module. import matplotlib.pyplot as plt import matplotlib.ticker as tck import numpy as np # Create Plot f,ax=plt.subplots(figsize=(7,4)) # Sample Data x=np.arange(-10.0,10.0,0.1) y=np.arctan(x) # Plot the data ax.plot(x/np.pi,y) # Customizing y-axis Ticks ax.yaxis.set_major_formatter(tck.FormatStrFormatter(”%g $pi$”)) ax.yaxis.set_major_locator(tck.MultipleLocator(base=0.5)) plt.grid() plt.show() Output On executing the above code we will get the following output − Custom Package for Radian Ticks A custom package named “basic_units.py” can denote the tick marks using the radians. This package is not part of the standard or widely recognized packages and needs to be downloaded separately(available in the examples folder of Matplotlib). Example This example demonstrates how to create a plot with radians using the basic_units mockup example package. import matplotlib.pyplot as plt from basic_units import radians import numpy as np # Create Plot f,ax=plt.subplots(figsize=(7,4)) x = np.arange(-10.0,10.0,0.1) y = list(map(lambda y: y*radians,np.arctan(x))) x = list(map(lambda x: x*radians,x)) ax.plot(x,y,”b.”) plt.xlabel(”radians”) plt.ylabel(”radians”) plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – LaTeX

Matplotlib – Latex ”; Previous Next What is LaTeX? LaTeX is a typesetting system widely used for producing scientific and technical documents, particularly in disciplines such as mathematics, physics, computer science, engineering and academic writing. It”s highly regarded for its superior typesetting of complex mathematical equations, scientific notations, and structured text formatting. Key Aspects of LaTeX The below are the key aspects of LaTeX. Markup Language − LaTeX is a markup language, meaning it uses commands and tags to format text rather than WYSIWYG which is abbreviated as What You See Is What You Get editors. Users write plain text with embedded commands that specify the structure and formatting. High-Quality Typesetting − LaTeX excels in producing professional-looking documents with precise typographical and typesetting features. It handles complex structures like mathematical formulas, tables, bibliographies and cross-references exceptionally well. Package System − LaTeX offers a vast array of packages that extend its functionality for specific tasks or document types, providing templates, styles and additional features. Free and Open Source − LaTeX is free to use and is supported by a strong open-source community by ensuring continuous development and a rich ecosystem of packages and resources. Components of LaTeX − The LaTex of matplotlib library have the following components. Let’s see each of them in detail. Document Class − The document class specifies the type of document being created and defines its overall structure, layout and formatting. It acts as a template that sets the style and behaviour for the entire document. Different document classes are available to suit various types of documents such as articles, reports, books, presentations and more. Preamble − In LaTeX the preamble is the section of the document that precedes the main content and the begin{document} command. It is where we define the document settings, load packages, set parameters and configure global settings that apply to the entire document. The preamble acts as a setup area where we prepare LaTeX for processing the main body of the document. Document Body − The document body in LaTeX is the main section where the content of our document resides. It starts after the preamble and the begin{document} command and continues until the end{document} command. This section includes the actual text, sections, subsections, equations, figures, tables and any other elements that constitute the core content of the document. Advantages of LaTeX The following are the advantages of LaTex. Quality Typesetting − Produces high-quality output, especially for scientific and technical documents. Cross-Referencing − Simplifies referencing and cross-referencing of equations, figures, tables, and sections. Version Control − Facilitates version control and collaboration through plain text-based files. Customization − Allows extensive customization of document styles, layouts and formatting. Disadvantages of LaTeX Learning Curve − Requires learning its syntax and commands which can be daunting for beginners. Limited WYSIWYG − Lack of immediate visual feedback (WYSIWYG) might be challenging for some users accustomed to graphical editors. Usage of LaTeX Academic Writing − Academic papers, theses, dissertations Scientific − Scientific reports, articles, and journals Technical Documents − Technical documentation, manuals Presentations − Presentations using tools like Beamer Basic document structure of the LaTex Syntax A basic LaTeX document structure includes − documentclass{article} begin{document} section{Introduction} This is a simple LaTeX document. subsection{Subsection} Some text in a subsection. end{document} The above code defines a basic article document with a hierarchical structure comprising a section and a subsection. Writing our own LaTeX preamble To write our own LaTeX preamble in Matplotlib we can use this example as reference. Example 1 import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-10, 10, 100) y = np.exp(x) plt.plot(x, y, color=”red”, label=”$y=e^{x}$”) plt.legend(loc=”upper right”) plt.show() Output This will generate the following output − Example 2 In this example we are using the Latex formula in the legend of a plot inside a .py file. import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(1, 10, 1000) y = np.sin(x) plt.plot(x, y, label=r”$sin (x)$”, c=”red”, lw=2) plt.legend() plt.show() Output This will generate the following output − Put a little more complex equation in the label, for example, label=r”αiπ+1=0”. Now look at the legend at the top-right corner of the plot. Example 3 import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(1, 10, 1000) y = np.sin(x) plt.plot(x, y, label=r”$sin (x)$”, c=”red”, lw=2) plt.legend(r”αiπ+1=0”) plt.show() Output This will generate the following output − Rendering mathematical expressions Rendering mathematical expressions in LaTeX involves using LaTeX syntax to write mathematical equations, symbols and formulas. LaTeX provides a comprehensive set of commands and notation to create complex mathematical expressions with precision and clarity. Importance of LaTeX for Mathematics Precision and Clarity − LaTeX allows precise typesetting of mathematical notation and symbols. Consistency − Maintains consistency in formatting across mathematical documents. Publication-Quality − Produces high-quality mathematical expressions suitable for academic and scientific publications. LaTeX”s support for mathematical typesetting makes it a preferred choice for researchers, mathematicians, scientists and academics when writing technical or mathematical documents that require accurate and well-formatted mathematical notation. LaTeX for Mathematical Expressions The below are the components of LaTex in Mathematical Expressions. Inline Math Mode − Inline math mode in LaTeX is used to include mathematical expressions within the text of a document. We can use inline math mode by enclosing the mathematical expression between a pair of single dollar signs $…$. Using the inline math mode − In this example the mathematical expression `frac{-b