Matplotlib – Arrows

Matplotlib – Arrows ”; Previous Next What are Arrows in Matplotlib? In Matplotlib library Arrows refer to the graphical elements used to indicate direction, connection between points and to highlight specific features within plots. Arrows can be added to plots using the plt.arrow() function or incorporated within annotations by using the plt.annotate() function. Arrows in Matplotlib library are versatile elements used to visually depict directionality, connections or highlights within the plots for aiding in better communication of information in visualizations. We can adjust parameters like coordinates, lengths, colors and styles to suit the specific visualization needs. The plt.arrow() function in matplotlib library creates arrows between two points on a plot. Syntax The following is the syntax and parameters of the plt.arrow() function. plt.arrow(x, y, dx, dy, kwargs) Where, x, y − These are the starting point coordinates of the arrow. dx, dy − These are lengths of the arrow in the x and y directions. kwargs − We can add additional keyword arguments to customize arrow properties such as color, width, style etc. Adding arrows to the line plot In this example we are plotting a plot by creating the arrows between the given two points on the plot by using the plt.arrow() function. To this function we passed the x, y, dx and dy points as input parameters for creating arrows in those mentioned points. In addition we passed the parameters such as length, width and color of the arrow. Example import matplotlib.pyplot as plt # Creating a line plot plt.plot([0, 1], [0, 1]) # Adding an arrow plt.arrow(0.2, 0.2, 0.4, 0.4, head_width=0.05, head_length=0.1, fc=”red”, ec=”blue”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Arrow created by using plt.arrow() function”) # show grid of the plot plt.grid(True) plt.show() Output Adding arrow separately Here this is another example of creating the arrows. As we know arrows can also be integrated into annotations using plt.annotate() by specifying arrowprops to define arrow styles. In this example ”Arrow Annotation” is connected to point (0.5, 0.5) with an arrow style specified by arrowprops. Example import matplotlib.pyplot as plt # Creating a plot plt.plot([0, 1], [0, 1]) # Adding an arrow with annotation plt.annotate(”Arrow Annotation”, xy=(0.5, 0.5), xytext=(0.2, 0.2), arrowprops=dict(facecolor=”yellow”,ec = ”red”, arrowstyle=”->”)) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Arrow Annotation Example”) # Displaying the grid plt.grid(True) plt.show() Output Plotting distance arrows in technical drawing To plot the distance arrows in technical drawing in matplotlib we can use annotate() method with arrow properties. Example from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True plt.axhline(3.5) plt.axhline(2.5) plt.annotate( ””, xy=(0.5, 3.5), xycoords=”data”, xytext=(0.5, 2.5), textcoords=”data”, arrowprops={”arrowstyle”: ””}) plt.annotate( ”$it{d=1}$”, xy=(0.501, 3.0), xycoords=”data”, xytext=(0.5, 3.5), textcoords=”offset points”) plt.show() Output Print Page Previous Next Advertisements ”;

Matplotlib – Font Properties

Matplotlib – Font Properties ”; Previous Next What are Font properties? In Matplotlib library font properties are attributes that determine the appearance and styling of text elements within plots and figures. These properties include various aspects such as font family, size, weight, style and other settings that affect the visual presentation of text. Key Font Properties in Matplotlib Font Family The Font family specifies the typeface or used for text elements. Common families include serif, sans-serif, monospace etc. serif − Fonts with decorative strokes often used for a more traditional or formal appearance. sans-serif − Fonts without decorative strokes known for a clean and modern look which are commonly used for readability. monospace − Fonts where each character occupies the same amount of horizontal space, often used for code or tabular data. Custom or Specific Fonts − Users can also use custom fonts installed on their system or provide font paths for specific typefaces. Font Size The Font size determines the size of the text in points (pt) influencing readability and visibility. Font size is specified in points (pt) where 1 point is approximately 1/72 inch. Matplotlib uses points as a standard unit for font size by allowing for consistency across different devices and display resolutions. Font Weight The Font weight controls the thickness or boldness of the text. Options range from normal to bold. It allows users to control the visual emphasis of text elements such as labels, titles, annotations and other textual components. Font Weight Options normal − Specifies normal font weight. bold − Specifies a bold font weight. Integer Values − Some fonts support numeric values ranging from 100 to 900 to specify the weight level. Font Style The Font style specifies the style of the text such as normal, italic or oblique. It allows users to control the slant or style of the text elements such as labels, titles, annotations and other textual components. Font Style Options normal − Specifies normal font style (no slant or italicization). italic − Specifies italic font style slanting the characters. oblique − Similar to italic but may differ slightly in appearance in some fonts. Setting Font Properties in Matplotlib The following are the ways to set the font properties in matplotlib. Global Configuration (using plt.rcParams) This is used to configure default font properties for all text elements in a plot or figure. Example import matplotlib.pyplot as plt # Set global font properties x = [2,3,4,6] y = [9,2,4,7] plt.rcParams[”font.family”] = ”sans-serif” plt.rcParams[”font.size”] = 8 plt.rcParams[”font.weight”] = ”normal” plt.rcParams[”font.style”] = ”italic” plt.plot(x,y) plt.xlabel(“x-axis”) plt.ylabel(“y-axis”) plt.title(“Setting fonts globally”) plt.show() Output Individual Text Elements Through this method we can set font properties for specific text elements within a plot. Example import matplotlib.pyplot as plt # Set Individual font properties x = [2,3,4,6] y = [9,2,4,7] plt.plot(x,y) plt.xlabel(”X-axis Label”, fontsize=14, fontweight=”bold”, fontstyle=”italic”) plt.ylabel(”Y-axis Label”, fontsize=14, fontweight=”bold”, fontstyle=”normal”) plt.title(“Setting fonts Individually”) plt.show() Output Importance of Font Properties The below are the importance of the font properties. Readability Proper font selection and size enhance the legibility of text elements. Aesthetics Font styles and families contribute to the visual appeal of plots. Communication Font properties aid in conveying emphasis or context within visualizations. Using Font Properties for Customization Adjusting font properties allows users to tailor the appearance of text to match the requirements of the visualization or presentation. Consistent and appropriate use of font properties ensures a visually cohesive and informative display of textual information within plots and figures. Finally we can font properties in Matplotlib library provide users with the flexibility to customize text appearance, ensuring clarity, readability and visual appeal in visualizations. These properties enable precise control over how text elements are displayed within plots helping effectively communicate information to viewers. Multiple font sizes in one label In this example we use multiple font sizes in one label in Python with the help of fontsize parameter in title() method. Example 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(-5, 5, 100) y = np.cos(x) plt.plot(x, y) fontsize = 20 plt.title(“$bf{y=cos(x)}$”, fontsize=fontsize) plt.axis(”off”) plt.show() Output Change the text color of font in the legend Here in this example we will change the text color of the font in the legend. Example import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-2, 2, 100) y = np.exp(x) plt.plot(x, y, label=”y=exp(x)”, c=”red”) leg = plt.legend(loc=”upper left”) for text in leg.get_texts(): text.set_color(“green”) plt.show() Output Change the default font color for all text In this example we will change the default font color for all the text in the plot. Example import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True print(“Default text color is: “, plt.rcParams[”text.color”]) plt.rcParams.update({”text.color”: “red”, ”axes.labelcolor”: “green”}) plt.title(“Title”) plt.xlabel(“X-axis”) plt.show() Output Default text color is: black Change the font size of ticks of axes object In this example we will change the default font color for all the text in the plot. Example import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.linspace(-2, 2, 10) y = np.sin(x) fig, ax = plt.subplots() ax.plot(x, y, c=”red”, lw=5) ax.set_xticks(x) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(14) tick.label.set_rotation(”45”) plt.tight_layout() plt.show() Output Increase the font size of the seaborn plot legend In this example we increase the font size of the legend in a Seaborn plot, we can use the fontsize variable and can

Matplotlib – Path Editor

Matplotlib – Path Editor ”; Previous Next A Path Editor is an application that allows users to interactively edit and manipulate paths in a graphical environment. In the context of Matplotlib, a Path Editor typically refers to a graphical user interface (GUI) application that facilitates the editing of paths defined using Matplotlib”s Path class. Before diving into the Path Editor, it”s essential to understand the basics of Matplotlib paths. A Path is a fundamental object in Matplotlib that contains various elements like line segments, curves, and shapes within the matplotlib.patches module. Paths provide a versatile way to define complex outlines by specifying a series of commands such as moveto, lineto, and curveto. Matplotlib offers a powerful Path class that serves as the foundation for creating and manipulating paths in visualizations. Step by Step implementation In this tutorial, we”ll explore the Matplotlib Path Editor, a cross-GUI application that uses Matplotlib”s event handling capabilities to edit and modify paths on the canvas interactively. Creating the PathInteractor class Create a path editor (PathInteractor) class to handle the interaction with the defined path. This class includes methods to toggle vertex markers (using the ”t” key), drag vertices, and respond to mouse and key events. Example import matplotlib.pyplot as plt import numpy as np from matplotlib.backend_bases import MouseButton from matplotlib.patches import PathPatch from matplotlib.path import Path class PathInteractor: showverts = True # max pixel distance to count as a vertex hit epsilon = 5 def __init__(self, pathpatch): # Initialization and event connections self.ax = pathpatch.axes canvas = self.ax.figure.canvas self.pathpatch = pathpatch self.pathpatch.set_animated(True) x, y = zip(*self.pathpatch.get_path().vertices) self.line, = ax.plot( x, y, marker=”o”, markerfacecolor=”r”, animated=True) self._ind = None # the active vertex canvas.mpl_connect(”draw_event”, self.on_draw) canvas.mpl_connect(”button_press_event”, self.on_button_press) canvas.mpl_connect(”key_press_event”, self.on_key_press) canvas.mpl_connect(”button_release_event”, self.on_button_release) canvas.mpl_connect(”motion_notify_event”, self.on_mouse_move) self.canvas = canvas def get_ind_under_point(self, event): # Return the index of the point closest to the event position or *None* xy = self.pathpatch.get_path().vertices xyt = self.pathpatch.get_transform().transform(xy) # to display coords xt, yt = xyt[:, 0], xyt[:, 1] d = np.sqrt((xt – event.x)**2 + (yt – event.y)**2) ind = d.argmin() return ind if d[ind] < self.epsilon else None def on_draw(self, event): # Callback for draws. self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self.pathpatch) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) def on_button_press(self, event): # Callback for mouse button presses if (event.inaxes is None or event.button != MouseButton.LEFT or not self.showverts): return self._ind = self.get_ind_under_point(event) def on_button_release(self, event): # Callback for mouse button releases if (event.button != MouseButton.LEFT or not self.showverts): return self._ind = None def on_key_press(self, event): # Callback for key presses if not event.inaxes: return if event.key == ”t”: self.showverts = not self.showverts self.line.set_visible(self.showverts) if not self.showverts: self._ind = None self.canvas.draw() def on_mouse_move(self, event): # Callback for mouse movements if (self._ind is None or event.inaxes is None or event.button != MouseButton.LEFT or not self.showverts): return vertices = self.pathpatch.get_path().vertices vertices[self._ind] = event.xdata, event.ydata self.line.set_data(zip(*vertices)) self.canvas.restore_region(self.background) self.ax.draw_artist(self.pathpatch) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) Event Handling and Canvas Interaction The PathInteractor class connects various callbacks to canvas events, enabling users to interact with the defined path. These interactions include pressing and releasing mouse buttons, dragging vertices, and toggling vertex markers with key presses. canvas.mpl_connect(”draw_event”, self.on_draw) canvas.mpl_connect(”button_press_event”, self.on_button_press) canvas.mpl_connect(”key_press_event”, self.on_key_press) canvas.mpl_connect(”button_release_event”, self.on_button_release) canvas.mpl_connect(”motion_notify_event”, self.on_mouse_move) Defining and Visualizing a Path Start by defining a predefined path, consisting of various path codes and vertices, which is created using the Matplotlib Path class. This path is then visualized on the canvas using a PathPatch instance, adding an interactive component to the plot. fig, ax = plt.subplots() pathdata = [ (Path.MOVETO, (1.58, -2.57)), (Path.CURVE4, (0.35, -1.1)), (Path.CURVE4, (-1.75, 2.0)), (Path.CURVE4, (0.375, 2.0)), (Path.LINETO, (0.85, 1.15)), (Path.CURVE4, (2.2, 3.2)), (Path.CURVE4, (3, 0.05)), (Path.CURVE4, (2.0, -0.5)), (Path.CLOSEPOLY, (1.58, -2.57)), ] codes, verts = zip(*pathdata) path = Path(verts, codes) patch = PathPatch( path, facecolor=”green”, edgecolor=”yellow”, alpha=0.5) ax.add_patch(patch) Running the Path Editor Instantiate the PathInteractor class, set plot properties, and display the plot. Users can now interactively drag vertices, toggle vertex markers using the key “t”, and observe real-time updates. interactor = PathInteractor(patch) ax.set_title(”drag vertices to update path”) ax.set_xlim(-3, 4) ax.set_ylim(-3, 4) plt.show() Example Let’s see the complete example of the Matplotlib Path Editor. import matplotlib.pyplot as plt import numpy as np from matplotlib.backend_bases import MouseButton from matplotlib.patches import PathPatch from matplotlib.path import Path class PathInteractor: showverts = True # max pixel distance to count as a vertex hit epsilon = 5 def __init__(self, pathpatch): # Initialization and event connections self.ax = pathpatch.axes canvas = self.ax.figure.canvas self.pathpatch = pathpatch self.pathpatch.set_animated(True) x, y = zip(*self.pathpatch.get_path().vertices) self.line, = ax.plot( x, y, marker=”o”, markerfacecolor=”r”, animated=True) self._ind = None # the active vertex canvas.mpl_connect(”draw_event”, self.on_draw) canvas.mpl_connect(”button_press_event”, self.on_button_press) canvas.mpl_connect(”key_press_event”, self.on_key_press) canvas.mpl_connect(”button_release_event”, self.on_button_release) canvas.mpl_connect(”motion_notify_event”, self.on_mouse_move) self.canvas = canvas def get_ind_under_point(self, event): # Return the index of the point closest to the event position or *None* xy = self.pathpatch.get_path().vertices xyt = self.pathpatch.get_transform().transform(xy) # to display coords xt, yt = xyt[:, 0], xyt[:, 1] d = np.sqrt((xt – event.x)**2 + (yt – event.y)**2) ind = d.argmin() return ind if d[ind] < self.epsilon else None def on_draw(self, event): # Callback for draws. self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self.pathpatch) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) def on_button_press(self, event): # Callback for mouse button presses if (event.inaxes is None or event.button != MouseButton.LEFT or not self.showverts): return self._ind = self.get_ind_under_point(event) def on_button_release(self, event): # Callback for mouse button releases if (event.button != MouseButton.LEFT or not self.showverts): return self._ind = None def on_key_press(self, event): # Callback for key presses if not event.inaxes: return if event.key == ”t”: self.showverts = not self.showverts self.line.set_visible(self.showverts) if not self.showverts: self._ind = None self.canvas.draw() def on_mouse_move(self, event): # Callback for mouse movements if (self._ind is None or event.inaxes is None or event.button != MouseButton.LEFT or not self.showverts): return vertices = self.pathpatch.get_path().vertices vertices[self._ind] =

Matplotlib – Timers

Matplotlib – Timers ”; Previous Next In general computer programming, timers are refers to a mechanism that allows users to schedule the execution of a specific task or code snippet at predefined intervals. Timers are useful for various applications, enabling the automation of repetitive actions, periodic updates, or the triggering of events based on time-related conditions. Timers in Matplotlib Matplotlib timers are powerful features that enable you to integrate periodic events into the plots. And designed to work independently of specific graphical user interface (GUI) backends. To utilize the Matplotlib timers feature, the figure.canvas.new_timer() function works as a key component to integrate timers with various GUI event loops. While its call signature may appear unconventional, due to this understanding the call signature is crucial (you need to explicitly specify the empty sequences and dictionaries if your call back function(s) don”t take arguments or keyword arguments). Here is the syntax − Syntax timer = figure.canvas.new_timer(interval=5000, callbacks=[(callback_function, [], {})]) timer.start() This syntax creates a timer with a 5-second interval, demonstrating the timer”s integration into Matplotlib plots. Example Here is an example, That demonstrates a simple usage of timers in Matplotlib. It sets up a timer to print “Matplotlib Timer Event” to the console every 5 seconds. This showcases how timers can be employed for periodic tasks within plots. import matplotlib.pyplot as plt # Function to handle the timer event def handle_timer_event(): print(”Matplotlib Timer Event”) # Create a new Matplotlib figure and axis custom_fig, custom_ax = plt.subplots(figsize=(7, 4)) # Create a timer with a 5000 milliseconds interval custom_timer = custom_fig.canvas.new_timer(interval=5000, callbacks=[(handle_timer_event, [], {})]) # Start the timer custom_timer.start() plt.show() Output On executing the above program you will get the following output − Matplotlib Timer Event Matplotlib Timer Event Matplotlib Timer Event Matplotlib Timer Event Matplotlib Timer Event Matplotlib Timer Event Watch the video below to observe the works of this example. Timer for Real-Time Updates Timers can be used to achieve real-time updates within a plot, enhancing the dynamic nature of visualizations. Example In the example, a timer is used to update the title of a figure with the current timestamp at intervals of 500 milliseconds. Which shows that, how timers can be used for dynamic, time-sensitive updates in visualizations. from datetime import datetime import matplotlib.pyplot as plt import numpy as np # Function to update the title with the current timestamp def update_title(axes): axes.set_title(datetime.now()) axes.figure.canvas.draw() # Create a Matplotlib figure and axis fig, ax = plt.subplots(figsize=(7, 4)) # Generate sample data x = np.linspace(0, 10, 100) ax.plot(x, np.sin(x)) # Create a new timer with an interval of 500 milliseconds timer = fig.canvas.new_timer(interval=500) # Add the update_title function as a callback to the timer timer.add_callback(update_title, ax) # Start the timer timer.start() plt.show() Output On executing the above program you will get the following output − Watch the video below to observe the works of this example. Animated Brownian Walk with Timer In a more advanced scenario, we use the advantages of timers to animate a 2D Brownian walk, creating a visually dynamic plot that produces over time. Example This example demonstrates the application of timers in creating animated visualizations. import numpy as np import matplotlib.pyplot as plt # Callback function for the timer to update line data def update_line_data(line, x_data, y_data): x_data.append(x_data[-1] + np.random.normal(0, 1)) y_data.append(y_data[-1] + np.random.normal(0, 1)) line.set_data(x_data, y_data) line.axes.relim() line.axes.autoscale_view() line.axes.figure.canvas.draw() # Initial data points x_coords, y_coords = [np.random.normal(0, 1)], [np.random.normal(0, 1)] # Create a Matplotlib figure and axis fig, ax = plt.subplots(figsize=(7, 4)) line, = ax.plot(x_coords, y_coords, color=”aqua”, marker=”o”) # Create a new timer with a 100-millisecond interval animation_timer = fig.canvas.new_timer(interval=1000, callbacks=[(update_line_data, [line, x_coords, y_coords], {})]) animation_timer.start() # Display the animated plot plt.show() Output On executing the above program you will get a figure with animation − Watch the video below to observe the works of this example. Print Page Previous Next Advertisements ”;

Matplotlib – 3D Surface Plot

Matplotlib – 3D Surface Plots ”; Previous Next A 3D surface plot is a way to visualize data that has three dimensions: length, width, and height. Imagine a landscape with hills and valleys where each point on the surface represents a specific value. In a 3D surface plot, these points are plotted in a three-dimensional space, creating a surface that shows how the data varies across different positions. It is like looking at a three-dimensional map of the data, where the height of the surface represents the value of the data at each point. 3D Surface Plot in Matplotlib In Matplotlib, a 3D surface plot is a visual representation of multiple points connected like a graph with a specific area in three-dimensional space. We can create a 3d surface plot in Matplotlib using the plot_surface() function in “mpl_toolkits.mplot3d” module. It takes the X, Y, and Z coordinates as arrays and creates a continuous graph by joining the three coordinates. Let’s start by drawing a basic 3D surface plot. Basic 3D Surface Plot A basic 3D surface plot in Matplotlib is way of representing a graph in three dimensions, with X, Y, and Z axes. The coordinates form a surface where height or depth (Z-axis) at each point gives the plot its three-dimensional shape. Example In the following example, we are creating a basic 3D surface plot by evenly spacing the X and Y coordinates and then finding the Z coordinate based on the values of X and Y coordinates − import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D # Creating data x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) # Creating a 3D plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) # Plotting the basic 3D surface ax.plot_surface(X, Y, Z, cmap=”viridis”) # Customizing the plot ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_zlabel(”Z-axis”) ax.set_title(”Basic 3D Surface Plot”) # Displaying the plot plt.show() Output Following is the output of the above code − Parametric 3D Surface Plots Parametric 3D surface plots in Matplotlib use mathematical equations to define a graph in three-dimensional space. These equations describe how the values of X, Y, and Z coordinates changes with variations in parameter values. Example In here, we are creating a parametric 3D surface plot by parametrizing the X, Y, and Z coordinates with respect to initial data points (u, v), size (R) and thickness (r). The resulting plot shows a donut-shaped surface plot − import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D # Parametric equations for a torus def torus_parametric(u, v, R=1, r=0.3): x = (R + r * np.cos(v)) * np.cos(u) y = (R + r * np.cos(v)) * np.sin(u) z = r * np.sin(v) return x, y, z # Generating data u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, 2 * np.pi, 100) U, V = np.meshgrid(u, v) X, Y, Z = torus_parametric(U, V) # Creating a 3D plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) # Plotting the parametric 3D surface ax.plot_surface(X, Y, Z, cmap=”plasma”) # Customizing the plot ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_zlabel(”Z-axis”) ax.set_title(”Parametric 3D Surface Plot (Torus)”) # Displaying the plot plt.show() Output On executing the above code we will get the following output − Multiple 3D Surface Plots In Matplotlib, multiple 3D surface plots displays multiple graphs stacked on top of each other in a three-dimensional space. Each graph has a distinct value for the X, Y, and Z coordinates. Example The following example creates two 3D surface plots stacked on top of each other. We use different equations to create two distinct 3D surface plots. The resultant plot shows the two surface plots on different planes with different colors − import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D # Creating data for two surfaces x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z1 = np.sin(np.sqrt(X**2 + Y**2)) Z2 = np.exp(-(X**2 + Y**2)) # Creating a 3D plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) # Plotting the two surfaces surf1 = ax.plot_surface(X, Y, Z1, cmap=”viridis”, alpha=0.7) surf2 = ax.plot_surface(X, Y, Z2, cmap=”plasma”, alpha=0.7) # Customize the plot ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_zlabel(”Z-axis”) ax.set_title(”Multiple Surfaces in 3D Surface Plot”) # Adding a colorbar fig.colorbar(surf1, ax=ax, orientation=”vertical”, shrink=0.5, aspect=20) # Displaying the plot plt.show() Output After executing the above code, we get the following output − Interpolated 3D Surface Plots Interpolated 3D surface plots in Matplotlib help us to visualize a graph whose X, Y, and Z coordinates are scattered randomly. Interpolation helps to fill in the missing data points to create a continuous graph. Example Now, we are creating an interpolated 3D surface plots. We generate random values for the X, Y, and Z coordinates and then use linear interpolation to estimate the values of missing data points using nearest data points − import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import griddata # Creating irregularly spaced data np.random.seed(42) x = np.random.rand(100) y = np.random.rand(100) z = np.sin(x * y) # Creating a regular grid xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100) xi, yi = np.meshgrid(xi, yi) # Interpolating irregular data onto the regular grid zi = griddata((x, y), z, (xi, yi), method=”linear”) # Creating a 3D plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) # Plotting the 3D surface from irregular data using grid interpolation ax.plot_surface(xi, yi, zi, cmap=”viridis”, edgecolor=”k”) # Customizing the plot ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_zlabel(”Z-axis”) ax.set_title(”3D Surface Plot from Irregular Data (Grid Interpolation)”) # Displaying the plot plt.show() Output On executing

Matplotlib – Scales

Matplotlib – Scales ”; Previous Next What are Scales in Matplotlib? In Matplotlib library scales refer to the mapping of data values to the physical dimensions of a plot. They determine how data values are represented and visualized along the axes of a plot. Matplotlib supports various types of scales and the choice of scale can significantly impact how the data is perceived in visualization. The below are the common types of scales available in matplotlib library. Linear Scale − Suitable for most numerical data without large variations in magnitude. Logarithmic Scale − Ideal for datasets covering several orders of magnitude or exhibiting exponential growth. Symmetrical Logarithmic Scale − Suitable for datasets with both positive and negative values. Let us go through these one by one. Linear Scale The linear scale is the default scale used to represent data along axes in a plot. It”s a straightforward mapping where the data values are plotted in direct proportion to their actual numerical values. In a linear scale equal distances along the axis represent equal differences in the data. Characteristics of Linear Scale Equal Intervals − In a linear scale equal distances on the axis correspond to equal differences in data values. Linear Mapping − The relationship between data values and their position on the axis is linear. Using Linear Scale By default the Matplotlib library uses a linear scale for both the x-axis and y-axis. To explicitly set a linear scale we don”t need to use any specific function as it”s the default behavior. However we can specify it explicitly using plt.xscale(”linear”) or plt.yscale(”linear”) for the x-axis or y-axis respectively. The following is the example of applying the linear scale to a plot. Example import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.plot(x, y) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Linear Scale”) plt.show() Output Following is the output of the above program − When to Use Linear Scale Linear scales are commonly used when the data doesn”t have exponential growth or when the range of values isn”t too large. It”s suitable for representing most numerical data that doesn”t exhibit significant nonlinear behavior. Logarithmic Scale The Logarithmic scale represents data using a logarithmic mapping. This is useful when there is a wide range of values and the logarithmic scale helps to emphasize changes in smaller values. Characteristics of Logarithmic Scale The below are the characteristics of the logarithmic scale − Equal Ratios − In a logarithmic scale, equal distances on the axis represent equal ratios between values rather than equal differences. Compression of Data − It compresses a wide range of data into a more readable and interpretable visualization. Emphasizes Smaller Values − It emphasizes changes in smaller values more than larger ones. Using Logarithmic Scale To use a logarithmic scale we have to specify plt.xscale(”log”) or plt.yscale(”log”) for the x-axis or y-axis respectively. Logarithmic scales are particularly useful for visualizing exponential growth or phenomena that cover several orders of magnitude. When to Use Logarithmic Scale Logarithmic scales are suitable for data with large variations in magnitude or when there”s a need to highlight changes in smaller values. Commonly used in fields like finance (stock prices), scientific research (decibel levels, earthquake magnitudes) and biology (pH levels). Example The following is the example plot with the logarithmic scale − import matplotlib.pyplot as plt import numpy as np # Generating logarithmically spaced data x = np.linspace(1, 10, 100) y = np.log(x) # Creating a plot with a logarithmic scale for the x-axis plt.plot(x, y) plt.xscale(”log”) # Set logarithmic scale for the x-axis plt.xlabel(”X-axis (log scale)”) plt.ylabel(”Y-axis”) plt.title(”Logarithmic Scale”) plt.show() Output Following is the output of the above program − Using a logarithmic scale in a plot can provide insights into data with a wide range of values making it easier to visualize patterns and trends across different scales within the same plot. Logarithmic plot of a cumulative distribution function The example given below, shows the Logarithmic plot of a cumulative distribution function. Example import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True N = 100 data = np.random.randn(N) X2 = np.sort(data) F2 = np.array(range(N))/float(N) plt.plot(X2, F2) plt.xscale(”log”) plt.yscale(”log”) plt.show() Output Following is the output of the above program − Symmetrical Logarithmic Scale The Symmetrical Logarithmic scale is similar to the logarithmic scale. It often abbreviated as symlog which is a type of scale used to represent data on an axis where the values are distributed symmetrically around zero using logarithmic intervals. It provides a logarithmic-like scale for both positive and negative values while accommodating zero. To apply the Symmetrical Logarithmic scale on x-axis and y-axis, we have to use plt.xscale(‘symlog’) and plt.yscale(‘symlog’) respectively. Characteristics of Symmetrical Logarithmic Scale The symmetrical logarithmic scale has the following characteristics. Symmetrical Behaviour − Represents both positive and negative values logarithmically while handling zero. Linear Near Zero − The scale is linear around zero within a specified range (linthresh) before transitioning to logarithmic behaviour. Parameters for Symmetrical Logarithmic Scale linthresh − Linear threshold that determines the range around zero where the scale behaves linearly before transitioning to a logarithmic scale. When to Use Symmetrical Logarithmic Scale: Data around Zero − Suitable for datasets containing values centered around zero with a wide range of positive and negative values. Avoiding Symmetry Bias − When symmetric representation of positive and negative values is needed without bias towards either side. Importance of Symmetrical Logarithmic Scale The Symmetrical Logarithmic Scale provides a logarithmic-like scale that accommodates both

Matplotlib – Poly Editor

Matplotlib – Poly Editor ”; Previous Next Poly Editor is short for Polygon Editor is an application that allows users to interactively edit and manipulate vertices of a polygon in a graphical environment. In the context of Matplotlib, a Poly Editor typically refers to a cross-GUI application that allows users to interactively modify polygons displayed on a canvas. This application provides features such as adding, deleting, and moving vertices of a polygon, as well as adjusting its shape and position using mouse clicks and keybindings. This tutorial will demonstrate how to create a polygon editor using Matplotlib”s event handling capabilities. Creating the Polygon Interactor Class To create the Poly Editor, define a Python class called PolygonInteractor, which handles interactions with the polygon vertices. This class implements event handling methods to respond to user interactions − on_draw − Handles the drawing of the polygon and its vertices. on_button_press − Responds to mouse button presses to select vertices. on_button_release − Handles mouse button releases. on_key_press − Handles key presses to toggle vertex markers(using the ”t” key), delete vertices(using the ‘d’ key), or insert new vertices(using the ”i” key). on_mouse_move − Handles mouse movements to drag vertices and update the polygon. Below is the implementation of the PolygonInteractor class − class PolygonInteractor: showverts = True epsilon = 3 def __init__(self, ax, poly): if poly.figure is None: raise RuntimeError(”You must first add the polygon to a figure ” ”or canvas before defining the interactor”) self.ax = ax canvas = poly.figure.canvas self.poly = poly x, y = zip(*self.poly.xy) self.line = Line2D(x, y, marker=”o”, markerfacecolor=”r”, animated=True) self.ax.add_line(self.line) self.cid = self.poly.add_callback(self.poly_changed) self._ind = None # the active vert canvas.mpl_connect(”draw_event”, self.on_draw) canvas.mpl_connect(”button_press_event”, self.on_button_press) canvas.mpl_connect(”key_press_event”, self.on_key_press) canvas.mpl_connect(”button_release_event”, self.on_button_release) canvas.mpl_connect(”motion_notify_event”, self.on_mouse_move) self.canvas = canvas def on_draw(self, event): self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self.poly) self.ax.draw_artist(self.line) def poly_changed(self, poly): vis = self.line.get_visible() Artist.update_from(self.line, poly) self.line.set_visible(vis) # don”t use the poly visibility state def get_ind_under_point(self, event): xy = np.asarray(self.poly.xy) xyt = self.poly.get_transform().transform(xy) xt, yt = xyt[:, 0], xyt[:, 1] d = np.hypot(xt – event.x, yt – event.y) indseq, = np.nonzero(d == d.min()) ind = indseq[0] if d[ind] >= self.epsilon: ind = None return ind def on_button_press(self, event): if not self.showverts: return if event.inaxes is None: return if event.button != 1: return self._ind = self.get_ind_under_point(event) def on_button_release(self, event): if not self.showverts: return if event.button != 1: return self._ind = None def on_key_press(self, event): if not event.inaxes: return if event.key == ”t”: self.showverts = not self.showverts self.line.set_visible(self.showverts) if not self.showverts: self._ind = None elif event.key == ”d”: ind = self.get_ind_under_point(event) if ind is not None: self.poly.xy = np.delete(self.poly.xy, ind, axis=0) self.line.set_data(zip(*self.poly.xy)) elif event.key == ”i”: xys = self.poly.get_transform().transform(self.poly.xy) p = event.x, event.y # display coords for i in range(len(xys) – 1): s0 = xys[i] s1 = xys[i + 1] d = dist_point_to_segment(p, s0, s1) if d <= self.epsilon: self.poly.xy = np.insert( self.poly.xy, i+1, [event.xdata, event.ydata], axis=0) self.line.set_data(zip(*self.poly.xy)) break if self.line.stale: self.canvas.draw_idle() def on_mouse_move(self, event): if not self.showverts: return if self._ind is None: return if event.inaxes is None: return if event.button != 1: return x, y = event.xdata, event.ydata self.poly.xy[self._ind] = x, y if self._ind == 0: self.poly.xy[-1] = x, y elif self._ind == len(self.poly.xy) – 1: self.poly.xy[0] = x, y self.line.set_data(zip(*self.poly.xy)) self.canvas.restore_region(self.background) self.ax.draw_artist(self.poly) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) Defining Utility Function Define a utility function dist_point_to_segment to calculate the distance between a point and a line segment. This function is used to determine which vertex is closest to the mouse cursor during interaction. def dist_point_to_segment(p, s0, s1): s01 = s1 – s0 s0p = p – s0 if (s01 == 0).all(): return np.hypot(*s0p) p1 = s0 + np.clip((s0p @ s01) / (s01 @ s01), 0, 1) * s01 return np.hypot(*(p – p1)) Initializing the Polygon Editor To initialize the polygon editor, we need to create an instance of the PolygonInteractor class and pass it the axis object and the polygon object: if __name__ == ”__main__”: import matplotlib.pyplot as plt from matplotlib.patches import Polygon theta = np.arange(0, 2*np.pi, 0.2) r = 1.5 xs = r * np.cos(theta) ys = r * np.sin(theta) poly = Polygon(np.column_stack([xs, ys]), animated=True) fig, ax = plt.subplots() ax.add_patch(poly) p = PolygonInteractor(ax, poly) ax.set_title(”Click and drag a point to move it”) ax.set_xlim((-2, 2)) ax.set_ylim((-2, 2)) plt.show() Running the Poly Editor By executing the complete code provided below, we will get a Matplotlib window displaying a plot with a polygon. We can interact with the polygon by clicking and dragging its vertices, toggling vertex markers by pressing the ‘t’ key, pressing the ”d” key to delete vertices, and pressing the ”i” key to insert new vertices. Example import matplotlib.pyplot as plt import numpy as np from matplotlib.backend_bases import MouseButton from matplotlib.patches import PathPatch from matplotlib.path import Path class PathInteractor: showverts = True # max pixel distance to count as a vertex hit epsilon = 5 def __init__(self, pathpatch): # Initialization and event connections self.ax = pathpatch.axes canvas = self.ax.figure.canvas self.pathpatch = pathpatch self.pathpatch.set_animated(True) x, y = zip(*self.pathpatch.get_path().vertices) self.line, = ax.plot( x, y, marker=”o”, markerfacecolor=”r”, animated=True) self._ind = None # the active vertex canvas.mpl_connect(”draw_event”, self.on_draw) canvas.mpl_connect(”button_press_event”, self.on_button_press) canvas.mpl_connect(”key_press_event”, self.on_key_press) canvas.mpl_connect(”button_release_event”, self.on_button_release) canvas.mpl_connect(”motion_notify_event”, self.on_mouse_move) self.canvas = canvas def get_ind_under_point(self, event): # Return the index of the point closest to the event position or None xy = self.pathpatch.get_path().vertices xyt = self.pathpatch.get_transform().transform(xy) # to display coords xt, yt = xyt[:, 0], xyt[:, 1] d = np.sqrt((xt – event.x)**2 + (yt – event.y)**2) ind = d.argmin() return ind if d[ind] < self.epsilon else None def on_draw(self, event): # Callback for draws. self.background = self.canvas.copy_from_bbox(self.ax.bbox) self.ax.draw_artist(self.pathpatch) self.ax.draw_artist(self.line) self.canvas.blit(self.ax.bbox) def on_button_press(self, event): # Callback for mouse button presses if (event.inaxes is None or event.button != MouseButton.LEFT or not self.showverts): return self._ind =

Matplotlib – 3D Plotting

Matplotlib – 3D Plotting ”; Previous Next A 3D plotting is a way to represent three dimensional data in a graphical format. It allows you to visualize the information in three spatial dimensions, represented as X, Y, and Z coordinates. In 3D plots, data points are not only located on a flat plane but also have depth, creating a more detailed representation of the dataset. 3D Plotting in Matplotlib In Matplotlib, we can create a three-dimensional plot using the mpl_toolkits.mplot3d module. This module provides tools to create three-dimensional visualizations, including scatter plots, line plots, surface plots, and more. These plots provide a way to represent and explore data points or mathematical functions in three-dimensional space. You can customize aspects such as color, markers, labels, and perspective to convey information more effectively. We can integrate the numpy library with the mpl_toolkits.mplot3d module to generate multidimensional data, and different functions, such as scatter, plot_surface, or plot_wireframe. The mpl_toolkits.mplot3d Module The “mpl_toolkits.mplot3d” module in Matplotlib enhances the library”s capabilities for three-dimensional plotting. It introduces the “Axes3D” class, which enables the creation of 3D subplots. This module facilitates the visualization of data in three dimensions through functions such as scatter() for 3D scatter plots, plot_surface() for surface plots, and plot_wireframe() for wireframe representations. 3D Scatter Plot A 3D scatter plot in Matplotlib is a visualization where data points are represented as individual markers in a three-dimensional space. Each data point is defined by three values, corresponding to its positions along the X, Y, and Z axes. These axes create a three-dimensional grid, and each marker is placed at the specified coordinates in this space. We can create this type of plot using the scatter() function. Example In the following example, we are generating random 3D data points using NumPy and creating a 3D scatter plot with blue markers. We display the plot in a three-dimensional space, where the x, y, and z axes represent the coordinates of the points − import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # Generating random 3D data np.random.seed(42) n_points = 100 x = np.random.rand(n_points) y = np.random.rand(n_points) z = np.random.rand(n_points) # Creating a 3D scatter plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) ax.scatter(x, y, z, c=”blue”, marker=”o”) ax.set_xlabel(”X Axis”) ax.set_ylabel(”Y Axis”) ax.set_zlabel(”Z Axis”) ax.set_title(”3D Scatter Plot”) plt.show() Output The resulting plot shows a gradual color transition under the curve − 3D Line Plot A 3D line plot in Matplotlib is a graphical representation that shows the connection between a sequence of points in a three-dimensional space. Unlike traditional 2D line plots where points are connected on a flat plane, a 3D line plot extends into three dimensions, forming a continuous line in the X, Y, and Z axes. We can create 3D line plot in matplotlib using the plot() function. When we use this function in conjunction with the projection=”3d” setting, it enables the generation of 3D line plots. Example In here, we are generating data for a 3D line plot by defining coordinates (x, y, and z) based on a parameterized equation. The resulting plot displays a helical shape in three-dimensional space. The x, y, and z axes represent the respective coordinates − import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # Generating data for a 3D line plot theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = r * np.sin(theta) y = r * np.cos(theta) # Creating a 3D line plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) ax.plot(x, y, z, label=”3D Line Plot”) ax.set_xlabel(”X Axis”) ax.set_ylabel(”Y Axis”) ax.set_zlabel(”Z Axis”) ax.set_title(”3D Line Plot”) plt.show() Output On executing the above code we will get the following output − 3D Surface Plot A 3D surface plot in Matplotlib is a visual representation of a mathematical function or a dataset in three-dimensional space. Instead of using flat lines or markers, this plot uses a continuous surface to show how a variable changes across two input dimensions (X and Y) and is dependent on a third dimension (Z). We can create this type of plot using the plot_surface() function. Example In here, we are generating data for a 3D surface plot by calculating the sine of the Euclidean distance from the origin for each point on a grid. The resulting plot visualizes a surface that rises and falls based on the sine function. The x, y, and z axes represent the coordinates and the height of the surface − import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np # Generating data for a 3D surface plot x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) x, y = np.meshgrid(x, y) z = np.sin(np.sqrt(x**2 + y**2)) # Creating a 3D surface plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) ax.plot_surface(x, y, z, cmap=”viridis”) ax.set_xlabel(”X Axis”) ax.set_ylabel(”Y Axis”) ax.set_zlabel(”Z Axis”) ax.set_title(”3D Surface Plot”) plt.show() Output On executing the above code we will get the following output − 3D Bar Plot A 3D bar plot in Matplotlib is a visual representation where data is presented using rectangular bars in three-dimensional space. Similar to a regular bar plot where bars are positioned along two axes (X and Y), a 3D bar plot adds a third dimension (Z) to represent the height or magnitude of each bar. We can create this type of plot using the bar3d() function. Example In the example below, we are generating data for a 3D bar plot with five bars in both “x” and “y” directions. The height of each bar is determined by the values in the “z” array. The resulting plot visualizes a set of three-dimensional bars with varying

Matplotlib – 3D Contours

Matplotlib – 3D Contours ”; Previous Next 3D contours refer to the lines or curves that show the shape and height of objects in a three-dimensional space. These contours help us understand how high or low different parts of an object are. They are commonly used in fields like geography, engineering, and art to represent the shape of things in a more detailed way. For example, if you have a mountain, its 3D contours will show the slopes, valleys, and peaks from all sides. Similarly, if you have a sculpture of an animal, its 3D contours will describe the shape of its body, head, and limbs from various viewpoints − 3D Contours in Matplotlib In Matplotlib, 3D contours represent the surface of a three-dimensional object. It allows you to create 3D contour plots by providing your data points representing the x, y, and z coordinates. These points define the shape of the object you want to visualize. Then, Matplotlib can generate contour lines or surfaces to represent the contours of your 3D data. You can create 3d contours in Matplotlib using the contour3D() function in the “mpl_toolkits.mplot3d” module. This function accepts the three coordinates – X, Y, and Z as arrays and plots a line across the X and Y coordinate to show the outline or change in height of a 3D object along the z-axis. Let”s start by drawing a basic 3D contour. Basic 3D Contour A basic 3D contour in Matplotlib is like drawing elevation lines on a map but in three dimensions. It uses X, Y, and Z axes to show the changes in height of a surface across different points. Example In the following example, we are creating a basic 3D contour by first plotting the X and Y coordinates. Then, we take the sum of sine and cosine values of X and Y to get the change in elevation. The resultant plot displays the outline of the shape with different heights on Z axis − import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D # Creating data x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X) + np.cos(Y) # Creating a 3D plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) # Plotting the 3D contour ax.contour3D(X, Y, Z, 50, cmap=”viridis”) # Customizing the plot ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_zlabel(”Z-axis”) ax.set_title(”Basic 3D Contour Plot”) # Displaying the plot plt.show() Output Following is the output of the above code − Parametric 3D Contours Parametric 3D contours in Matplotlib represent outline of shapes at different heights using mathematical parameters in three dimensions. The contours are not only defined by the changes in X, Y, and Z coordinates but also by changes in the parameters. Example In here, we are parameterizing the X, Y, and Z coordinates based on the the size (R), thickeness (r) and initial coordinates (u, v) of the 3D object. The resultant plot creates a donut-shaped 3D contour − import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D # Parametric equations for a torus def torus_parametric(u, v, R=1, r=0.3): x = (R + r * np.cos(v)) * np.cos(u) y = (R + r * np.cos(v)) * np.sin(u) z = r * np.sin(v) return x, y, z # Creating data u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, 2 * np.pi, 100) U, V = np.meshgrid(u, v) X, Y, Z = torus_parametric(U, V) # Creating a 3D plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) # Plotting the parametric 3D contour ax.contour3D(X, Y, Z, 50, cmap=”plasma”) # Customizing the plot ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_zlabel(”Z-axis”) ax.set_title(”Parametric 3D Contour Plot (Torus)”) # Displaying the plot plt.show() Output On executing the above code we will get the following output − 3D Contours from Irregular Data In Matplotlib, 3D contours from irregular data show the outline of a 3D surface whose data points are random. In this type of contour, we calculate the missing data points by estimating the values based on the X, Y, and Z values. Example The following example creates a 3D contour from irregular data. Here, we calculate the missing data points and interpolate them linearly with known data points. This creates a smooth and continuous 3D contour as the result − import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import griddata # Creating irregularly spaced data np.random.seed(42) x = np.random.rand(100) y = np.random.rand(100) z = np.sin(x * y) # Creating a regular grid xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100) xi, yi = np.meshgrid(xi, yi) # Combining irregular data onto the regular grid zi = griddata((x, y), z, (xi, yi), method=”linear”) # Creating a 3D plot fig = plt.figure() ax = fig.add_subplot(111, projection=”3d”) # Plotting the 3D contour from irregular data on the regular grid ax.contour3D(xi, yi, zi, 50, cmap=”viridis”) # Customizing the plot ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_zlabel(”Z-axis”) ax.set_title(”3D Contour Plot from Irregular Data”) # Displaying the plot plt.show() Output After executing the above code, we get the following output − Contour Lines in 3D Contours In Matplotlib, contour lines in 3D contours visually represents the 3D contour of an object along with its contour lines in three dimensions. The contour lines represent the slope of a 3D contour and are represented in the XY plane as they do not have any Z value (no depth). The function “contour()” is used to show the contour lines of an object. Example Now, we are creating a 3D contour and contour lines of an object. We plot a 3D contour on the z-axis and the contour lines on the XY plane. The resultant plot

Matplotlib – Logarithmic Axes

Matplotlib – Logarithmic Axes ”; Previous Next What is Logarithmic axes? Logarithmic axes in Matplotlib allow for plots where one or both axes use a logarithmic scale rather than a linear scale. This scaling is particularly useful when dealing with a wide range of data values spanning several orders of magnitude. Instead of representing each unit equally as in linear scaling we can use logarithmic scaling which represents equal intervals in terms of orders of magnitude. Now before seeing the comparison between Linear axes and Logarithmic axes let’s go through the Linear Axes once. What is Linear Axes? Linear axes in the context of plotting and graphing refers to the standard Cartesian coordinate system where the axes are represented in a linear or arithmetic scale. In this system we have the following. X-Axis and Y-Axis − The horizontal axis is typically the x-axis representing one variable while the vertical axis is the y-axis representing another variable. Equal Spacing − The linear scale along each axis represents equal increments in the plotted values. For instance in a linear scale the distance between 0 and 1 is the same as the distance between 5 and 6. Proportional Representation − Each unit along the axis corresponds directly to a unit change in the represented value. For example moving from 10 to 11 represents the same increase as moving from 20 to 21. Straight Lines − Relationships between variables are represented as straight lines on a linear scale. For linear relationships the plotted data points form a straight line when connected. Applicability − Linear axes are suitable for visualizing data where the relationships between variables are linear or when the values being represented do not vary widely across the scale. Linear vs. Logarithmic Scales Linear and logarithmic scales are different ways to represent data on an axis in a plot each with distinct characteristics that suit different types of data distributions and visualizations.   Linear Axes Logarthmic Axes Scaling This used linear scaling; the distance between each value on the axis is uniform and represents an equal increment in the plotted quantity. Logarithmic scaling represents values based on orders of magnitude rather than linear increments. Each tick on the axis corresponds to a power of a base value (e.g., 10 or e). Intervals The units along the axis correspond directly to the data values. For example on a linear scale from 0 to 10, each unit (e.g., from 0 to 1, 1 to 2) represents an equal increment of 1. In a logarithmic scale, equal distances along the axis represent multiplicative factors rather than additive ones. For example on a log scale from 1 to 100, the distances might represent powers of 10 (1, 10, 100). Representation Linear axes are typically used for data where the relationship between plotted points is best described by a linear progression. Logarithmic axes are suitable for data that spans multiple orders of magnitude, such as exponential growth or decay. They compress large ranges of values, making them visually manageable. When to use Typically used for data that shows a linear relationship between variables or data that does not span a wide range of values. Useful for visualizing data that spans several orders of magnitude, especially when dealing with exponential growth or decay, frequency distributions, or data that concentrates in certain ranges with outliers. Plot Types of Logarithmic Scales There are different types of Logarithmic scales available in Logarithmic axes. Let’s see one by one. Logarithmic X-axis A logarithmic x-axis in a plot refers to an x-axis where the scale is logarithmic rather than linear. This scaling transforms the representation of data on the x-axis from a linear progression to a logarithmic progression by making it suitable for visualizing data that spans multiple orders of magnitude or exhibits exponential behavior along the x-axis. Characteristics of Logarithmic X-axis Scaling Method − Instead of representing values in equal increments along the x-axis as in linear scaling a logarithmic x-axis represents values based on powers of a base value (e.g., 10 or e). Unequal Spacing − Equal distances on the axis correspond to multiplicative factors or orders of magnitude rather than fixed intervals. Use Case − Logarithmic x-axes are valuable when dealing with datasets that cover a wide range of values such as exponential growth, large spans of time or data distributions that concentrate in specific ranges with outliers. Example In this example plt.xscale(”log”) function sets the x-axis to a logarithmic scale. It transforms the x-axis from a linear scale to a logarithmic scale allowing for better visualization of the data especially when dealing with exponential or wide-ranging x-values. import matplotlib.pyplot as plt import numpy as np # Generating sample data x = np.linspace(1, 1000, 100) y = np.sin(x) * np.log10(x) # Generating data for demonstration # Creating a plot with logarithmic x-axis plt.figure(figsize=(8, 4)) plt.plot(x, y) plt.xscale(”log”) # Set x-axis to logarithmic scale plt.xlabel(”X-axis (Logarithmic Scale)”) plt.ylabel(”Y-axis”) plt.title(”Plot with Logarithmic X-axis”) plt.show() Output A logarithmic x-axis provides a different perspective on data visualization, emphasizing exponential behavior or patterns across varying orders of magnitude along the x-axis. Logarithmic Y-axis A logarithmic y-axis we often denoted as a log scale on the y-axis, represents a scaling method in plotting where the values along the y-axis are displayed logarithmically rather than linearly. This scaling is particularly useful when dealing with data that spans several orders of magnitude. The logarithmic y-axis in Matplotlib allows for the effective visualization of data that covers a wide range of values by making it easier to observe patterns or trends that might not be apparent when using a linear