Matplotlib – Bar Graphs

Matplotlib – Bar Graphs ”; Previous Next A bar plot is a graphical representation of data where rectangular bars or columns are used to represent different categories. The height of each bar corresponds to the value it represents. The horizontal axis (x-axis) typically represents the categories or groups being compared, while the vertical axis (y-axis) represents the values or quantities associated with each category. Each bar starts at the axis and extends horizontally or vertically, depending on the orientation of the graph. Bar Graphs in Matplotlib We can create a bar graph in Matplotlib using the bar() function. We can specify the categories or positions for the bars along with their corresponding heights. To customize the graph, we can use additional options like colors, labels, and titles. The bar() Function The bar() function is used to create bar graphs. It takes two main parameters: the positions of the bars on the x-axis and the heights of the bars. Following is the syntax of bar() function in Matplotlib − Syntax plt.bar(x, height, width=0.8, align=”center”, color=None, label=None) Where, x is the positions of the bars on the x-axis. height is the heights of the bars. width (optional) is the width of the bars. Default is 0.8. align (optional) is alignment of the bars. Default is ”center”. color (optional) is the color of the bars. Default is None, which results in the default color. label (optional is a label for the legend. Let us start by drawing a basic vertical bar graph. Basic Vertical Bar Graph In a basic vertical bar graph, we represent data where each bar or column corresponds to different categories, and we use the heights of these bars to indicate the values associated with that category. Example In the following example, we have three categories (”Category A”, ”Category B”, ”Category C”) with corresponding values (15, 24, 30). We are then using the plt.bar() function to create a vertical bar graph, where each bar represents the value of its respective category − import matplotlib.pyplot as plt categories = [”Category A”, ”Category B”, ”Category C”] values = [15, 24, 30] plt.bar(categories, values, color=”skyblue”) plt.xlabel(”Categories”) plt.ylabel(”Values”) plt.title(”Basic Vertical Bar Graph”) plt.show() Output After executing the above code, we get the following output − Horizontal Bar Graph In a horizontal bar graph, we represent data by plotting bars horizontally along a horizontal axis (x-axis). In this type of graph, we associate the lengths of the bars with the values they represent, and we display the categories along the vertical axis (y-axis). Example In here, we are providing three categories (”Category X”, ”Category Y”, ”Category Z”) with corresponding values (40, 28, 35). We are then using the barh() function to create a horizontal bar graph, where each bar extends horizontally based on its value. We are also customizing the color of each bar by passing the color argument to the function − import matplotlib.pyplot as plt categories = [”Category X”, ”Category Y”, ”Category Z”] values = [40, 28, 35] plt.barh(categories, values, color=[”green”, ”orange”, ”blue”]) plt.xlabel(”Values”) plt.ylabel(”Categories”) plt.title(”Horizontal Bar Graph with Color Customization”) plt.show() Output Following is the output of the above code − Grouped Bar Graph In a grouped bar graph, we stack multiple vertical bars next to each other for different categories. It is useful when you want to compare values for the same subcategories across different groups. Example Now, we are providing three categories (”Category A”, ”Category B”, ”Category C”) with values for two different groups (Group 1 and Group 2). We are then using the bar() function twice, once for each group, and positioning the bars side by side for each category − import matplotlib.pyplot as plt import numpy as np # Defining categories and their corresponding values for two groups categories = [”Category A”, ”Category B”, ”Category C”] values1 = [15, 24, 30] values2 = [20, 18, 25] # Setting the width of the bars bar_width = 0.35 # Calculating bar positions for both groups bar_positions1 = np.arange(len(categories)) bar_positions2 = bar_positions1 + bar_width # Creating the first set of bars (Group 1) plt.bar(bar_positions1, values1, width=bar_width, label=”Group 1”, color=”skyblue”) # Create the second set of bars (Group 2) next to the first set plt.bar(bar_positions2, values2, width=bar_width, label=”Group 2”, color=”orange”) # Adding labels to the axes plt.xlabel(”Categories”) plt.ylabel(”Values”) # Adding a title to the graph plt.title(”Grouped Bar Graph”) # Displaying a legend to identify the groups plt.legend() # Showing the plot plt.show() Output On executing the above code we will get the following output − Stacked Bar Graph In a stacked bar graph, we put one bar on top of another. Each bar represents a category, and the height of the combined bars at each category shows the total value. It is useful for comparing the total values across categories. Example In the example below, we have three categories (”Category A”, ”Category B”, ”Category C”) with values for two different groups (Group 1 and Group 2). We are using the bar() function twice, but this time, the bars for Group 2 are stacked on top of the bars for Group 1. The bottom parameter called in the second bar() function indicates that Group 2 bars should start where Group 1 bars end − import matplotlib.pyplot as plt # Defining categories and values for two groups categories = [”Category A”, ”Category B”, ”Category C”] values1 = [15, 24, 30] values2 = [20, 18, 25] # Creating the first set of bars (Group 1) without any offset plt.bar(categories, values1, label=”Group 1”, color=”skyblue”) # Creating the second set of bars (Group 2) plotted with ”bottom” set to the values of Group

Matplotlib – Mouse Move

Matplotlib – Mouse Move ”; Previous Next In general computer programming and software design, the term mouse move refers to an action of moving a computer mouse device across a surface to create the corresponding cursor or pointer movement on-screen. Mouse Move in Matplotlib The mouse move event in Matplotlib allows users to capture the cursor”s position over a plotted figure. This capability enables the creation of interactive features, such as displaying information at the cursor location or updating visualizations in real time based on the cursor”s movements. In this tutorial, we will explore how to use Mouse movement events in Matplotlib to enhance interactive plots. This is done by connecting to the motion_notify_event, you can capture the cursor”s position and implement various actions, providing users with an intuitive way to explore and analyze plotted data. Example Let”s start with a simple example that prints the data and pixel coordinates as the mouse moves over output figure. import matplotlib.pyplot as plt import numpy as np # Input data for ploting a circle angs = np.linspace(0, 2 * np.pi, 10**6) rs = np.zeros_like(angs) + 1 xs = rs * np.cos(angs) ys = rs * np.sin(angs) # Create a figure fig, ax = plt.subplots(figsize=(7, 4)) # Plot the data plt.plot(xs, ys) # Function to handle the event def on_move(event): if event.inaxes: print(f”data coords {event.xdata}, {event.ydata},”, f”pixel coords {event.x}, {event.y}”) # connect the event with the callable function binding_id = plt.connect(”motion_notify_event”, on_move) # Display the plot plt.show() Output On executing the above program you will get the following output − From the above figure, you can continuously read the coordinates of the mouse when it is moved − data coords 0.22000000000192466, 0.8999999999988899, pixel coords 413, 324 data coords 0.21188940092360364, 0.9071428571417381, pixel coords 411, 325 data coords 0.20377880184528263, 0.9142857142845864, pixel coords 409, 326 data coords 0.19972350230612212, 0.9214285714274346, pixel coords 408, 327 data coords 0.1916129032278011, 0.9214285714274346, pixel coords 406, 327 data coords 0.1916129032278011, 0.9285714285702829, pixel coords 406, 328 data coords 0.18755760368864083, 0.9285714285702829, pixel coords 405, 328 data coords 0.18350230414948032, 0.9357142857131315, pixel coords 404, 329 data coords 0.17944700461031982, 0.9357142857131315, pixel coords 403, 329 data coords 0.1753917050711593, 0.9357142857131315, pixel coords 402, 329 data coords 0.1753917050711593, 0.9428571428559798, pixel coords 402, 330 data coords 0.1713364055319988, 0.9428571428559798, pixel coords 401, 330 data coords 0.1672811059928383, 0.949999999998828, pixel coords 400, 331 data coords 0.1632258064536778, 0.949999999998828, pixel coords 399, 331 Watch the video below to observe how the mouse move event feature works here. Real-Time Plotting of Mouse Movement It is possible to achieve near real-time plotting of mouse movement by using the motion_notify_event in matplotlib. This event allows you to capture the dynamic movement of the mouse cursor, enabling the creation of interactive and responsive visualizations. Example The following example demonstrates how to plot the mouse path in near real-time using Matplotlib. import matplotlib.pyplot as plt # Create the plot fig, ax = plt.subplots(figsize=(7, 4)) # Set the limits of the plot ax.set_xlim(0, 1920-1) ax.set_ylim(0, 1080-1) # Initialize lists to store mouse coordinates x,y = [0], [0] # create empty plot points, = ax.plot([], [], ”-”, color=”green”) # cache the background background = fig.canvas.copy_from_bbox(ax.bbox) def on_move(event): # Append the current mouse coordinates x.append(event.xdata) y.append(event.ydata) # Update the plot data points.set_data(x,y) # Restore the background fig.canvas.restore_region(background) # Redraw the points ax.draw_artist(points) # Fill in the axes rectangle fig.canvas.blit(ax.bbox) # Connect the on_move function to the motion_notify_event fig.canvas.mpl_connect(“motion_notify_event”, on_move) # Display the plot plt.show() Output On executing the above program you will get the following output − Watch the video below to observe how the mouse move event feature works here. Highlighting Triangles with TriFinder Using the TriFinder class from the matplotlib.tri module to identify triangles within a Triangulation. By combining it with the motion_notify_event, you can dynamically highlight the triangle where the mouse moved over the triangulated plot. Example This example demonstrates the use of a TriFinder object in Matplotlib. As the mouse is moved over a triangulation, the triangle under the cursor is highlighted, and the index of the triangle is displayed in the plot title. import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Polygon from matplotlib.tri import Triangulation def update_highlighted_triangle(triangle_index): if triangle_index == -1: points = [0, 0, 0] else: points = triangulation.triangles[triangle_index] xs = triangulation.x[points] ys = triangulation.y[points] highlighted_polygon.set_xy(np.column_stack([xs, ys])) def on_mouse_move(event): if event.inaxes is None: triangle_index = -1 else: triangle_index = tri_finder(event.xdata, event.ydata) update_highlighted_triangle(triangle_index) ax.set_title(f”In triangle {triangle_index}”) event.canvas.draw() # Create a Triangulation. num_angles = 16 num_radii = 5 min_radius = 0.25 radii = np.linspace(min_radius, 0.95, num_radii) angles = np.linspace(0, 2 * np.pi, num_angles, endpoint=False) angles = np.repeat(angles[…, np.newaxis], num_radii, axis=1) angles[:, 1::2] += np.pi / num_angles x_values = (radii*np.cos(angles)).flatten() y_values = (radii*np.sin(angles)).flatten() triangulation = Triangulation(x_values, y_values) triangulation.set_mask(np.hypot(x_values[triangulation.triangles].mean(axis=1), y_values[triangulation.triangles].mean(axis=1)) < min_radius) # Use the triangulation”s default TriFinder object. tri_finder = triangulation.get_trifinder() # Setup plot and callbacks. fig, ax = plt.subplots(subplot_kw={”aspect”: ”equal”}, figsize=(7, 4)) ax.triplot(triangulation, ”bo-”) highlighted_polygon = Polygon([[0, 0], [0, 0]], facecolor=”y”) # dummy data for (xs, ys) update_highlighted_triangle(-1) ax.add_patch(highlighted_polygon) fig.canvas.mpl_connect(”motion_notify_event”, on_mouse_move) plt.show() Output On executing the above program you will get the following output − Watch the video below to observe how the mouse move event feature works here. Print Page Previous Next Advertisements ”;

Matplotlib – Event Handling

Matplotlib – Event Handling ”; Previous Next In general programming, an event is defined as the change in the state of an object, that occurs when a user interacts with graphical user interface components, triggering a response from the application. Consider actions like clicking a button, moving the mouse, typing on the keyboard, selecting an item from a list, or scrolling a page – each of these activities is an event, describing a change in the state of the source. Whereas, event handling is the backbone of interactive software applications. Which is the mechanism that controls the response to these events, determining what should occur when a particular event takes place. Event Handling in Matplotlib Matplotlib works with various user interface toolkits, including wxPython, Tkinter, Qt, GTK, and MacOSX. To ensure consistent support for interactive features like panning and zooming across different interfaces, Matplotlib uses a GUI-neutral event handling API. This API was initially based on the GTK model, which was the first user interface Matplotlib supported. Connecting to Events The main idea behind event handling in Matplotlib is connecting a callback functions to events. A callback function is executed when a specific event, such as a mouse click or key press, occurs. This mechanism enables you to respond to user interactions and implement customized behavior. If needed, you can disconnect the callback using the connection ID obtained from the mpl_connect method. fig.canvas.mpl_disconnect(cid) Example This example demonstrates a basic implementation that prints the mouse click location and the pressed button on a Matplotlib plot. import matplotlib.pyplot as plt import numpy as np # Generate sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Create a Matplotlib figure and axis fig, ax = plt.subplots(figsize=(7, 4)) # Plot the data ax.plot(x, y) # Define a callback function to handle events def onclick(event): print(”%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f” % (”double” if event.dblclick else ”single”, event.button, event.x, event.y, event.xdata, event.ydata)) # Connect the event handler to the figure canvas cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above program you will get the following output − single click: button=1, x=271, y=266, xdata=3.220737, ydata=0.485644 single click: button=1, x=218, y=226, xdata=2.146083, ydata=0.200062 single click: button=3, x=218, y=226, xdata=2.146083, ydata=0.200062 single click: button=1, x=360, y=245, xdata=5.025346, ydata=0.335713 Watch the video below to observe the works of this example. Common Events in Matplotlib Matplotlib supports various events, each represented by a specific class − button_press_event − Triggered when a mouse button is pressed. button_release_event − Triggered when a mouse button is released. close_event − Triggered when the figure is closed. draw_event − Triggered when the canvas has been drawn but the screen widget is not updated. key_press_event − Triggered when a key is pressed. key_release_event − Triggered when a key is released. motion_notify_event − Triggered when the mouse moves. pick_event − Triggered when an artist in the canvas is selected. resize_event − Triggered when the figure canvas is resized. scroll_event − Triggered when the mouse scroll wheel is rolled. figure_enter_event − Triggered when the mouse enters a new figure. figure_leave_event − Triggered when the mouse leaves a figure. axes_enter_event − Triggered when the mouse enters a new axes. axes_leave_event − Triggered when the mouse leaves an axes. By using these events, you can create dynamic and interactive visualizations in matplotlib. Event Attributes All Matplotlib events inherit from the matplotlib.backend_bases.Event class, which has attributes like name, canvas, and guiEvent. Common attributes for MouseEvent include x, y, inaxes, xdata, and ydata. Example Let”s see this simple example where a line segment is generated with each mouse press on the plot. from matplotlib import pyplot as plt import numpy as np # LineBuilder Class # It creats line segments based on mouse clicks. class LineBuilder: def __init__(self, line): self.line = line self.xs = list(line.get_xdata()) self.ys = list(line.get_ydata()) self.cid = line.figure.canvas.mpl_connect(”button_press_event”, self) def __call__(self, event): if event.inaxes != self.line.axes: return self.xs.append(event.xdata) self.ys.append(event.ydata) self.line.set_data(self.xs, self.ys) self.line.figure.canvas.draw() # Create a figure and axis fig, ax = plt.subplots(figsize=(7, 4)) # Set the title ax.set_title(”Click to Build Line Segments”) # empty line line, = ax.plot([0], [0]) # Create an instance for LineBuilder class linebuilder = LineBuilder(line) # Show the Plot plt.show() Output On executing the above program you will get the following figure click on this figure to observe the working of this example − Watch the video below to observe working of this example. Detecting the Mouse moves To detect when the mouse enters or leaves a figure or an axes, we can connect to the figure/axes enter/leave events. Example Here is another example that demonstrates how to change frame colors when the mouse enters or leaves specific regions of the figure. import matplotlib.pyplot as plt def enter_axes(event): event.inaxes.patch.set_facecolor(”yellow”) event.canvas.draw() def leave_axes(event): event.inaxes.patch.set_facecolor(”white”) event.canvas.draw() def enter_figure(event): event.canvas.figure.patch.set_facecolor(”red”) event.canvas.draw() def leave_figure(event): event.canvas.figure.patch.set_facecolor(”grey”) event.canvas.draw() fig, axs = plt.subplots(2, figsize=(7, 4)) fig.suptitle(”Mouse Hover Over Figure or Axes to Trigger Events”) fig.canvas.mpl_connect(”figure_enter_event”, enter_figure) fig.canvas.mpl_connect(”figure_leave_event”, leave_figure) fig.canvas.mpl_connect(”axes_enter_event”, enter_axes) fig.canvas.mpl_connect(”axes_leave_event”, leave_axes) 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. Example Here is another example that demonstrates how to show mouse release event coordinates with Matplotlib from matplotlib import pyplot as plt plt.rcParams[”backend”] = ”TkAgg” plt.rcParams[“figure.figsize”] = [7, 4] plt.rcParams[“figure.autolayout”] = True # Define a callback function to handle events def onclick(event): print(event.button, event.xdata, event.ydata) # Create a Matplotlib figure and axis fig, ax = plt.subplots() # Plot the data ax.plot(range(10)) # Connect the

Matplotlib – Path Effects

Matplotlib – Path Effects ”; Previous Next A path effects refer to the ways in which a path (route) can be manipulated in computer graphics. A “path” is a line or shape that you create using a drawing tool, and “path effects” allow you to apply various modifications to that line or shape. Imagine you draw a simple line, and with path effects, you can make that line look wavy, dotted, or apply other visual changes without having to redraw it manually. It is like adding special effects to the path you have created, making your drawings more interesting and dynamic. Path Effects in Matplotlib You can use the “path_effects” module in matplotlib to enhance the visual representation of your plots by creating path effects. To get started, consider the “withStroke()” function within the “path_effects” module. This function allows you to add a stroke, or outline, to lines and markers. Path effects in Matplotlib allow you to enhance the appearance of lines and shapes in your plots by applying special visual effects to them. Simple Line with Shadow Path Effect In Matplotlib, creating a simple line with a shadow involves drawing a basic line on a plot and then enhancing it with a shadow effect to make it visually interesting. This effect gives the appearance of a shadow under the line, as if it were creating a subtle shade on the plotting surface. Example In the following example, we are drawing a wavy line, and then adding shadow effect to the line using the path_effects module. The shadow effect consists of a “gray” stroke, creating the appearance of a shadow behind the line. import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects import numpy as np # Generating data x = np.linspace(0, 10, 100) y = np.sin(x) # Creating a simple line plot fig, ax = plt.subplots() line, = ax.plot(x, y, label=”Simple Line”) # Adding a shadow effect to the line shadow_effect = path_effects.withStroke(linewidth=5, foreground=”gray”) line.set_path_effects([shadow_effect]) ax.set_title(”Simple Line with Shadow Effect”) plt.legend() plt.show() Output Following is the output of the above code − Dashed Line with Outline Path Effect Creating a dashed line with an outline path effect in Matplotlib involves drawing a dotted line on a plot and then enhancing it by adding a bold outline. To create an outline, you can draw another line on top of the dashed line with a thicker linewidth and a solid linestyle. Example In here, we are creating a dashed line and enhancing it with a “black” stroke outline to give the line a bold border and make it stand out. import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects import numpy as np # Generating data x = np.linspace(0, 10, 100) y = np.cos(x) # Creating a dashed line plot with outline fig, ax = plt.subplots() line, = ax.plot(x, y, linestyle=”dashed”, label=”Dashed Line”) # Adding an outline effect to the line outline_effect = path_effects.withStroke(linewidth=3, foreground=”black”) line.set_path_effects([outline_effect]) ax.set_title(”Dashed Line with Outline Effect”) plt.legend() plt.show() Output On executing the above code we will get the following output − Bold Outlined Scatter Plot Path Effect Creating a bold outlined scatter plot with path effects in Matplotlib involves plotting a set of points on a graph and enhancing each point by adding a strong outline. Example In the example below, we generate a scatter with random data points. To enhance the visibility of these points, we apply a bold outline effect to each one by adding a “black” stroke with an increased “linewidth” around each scatter point. import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects import numpy as np # Generating data x = np.random.rand(50) y = np.random.rand(50) # Creating a scatter plot with bold outline effect fig, ax = plt.subplots() scatter = ax.scatter(x, y, label=”Scatter Plot”) # Adding a bold outline effect to the scatter points outline_effect = path_effects.withStroke(linewidth=3, foreground=”black”) scatter.set_path_effects([outline_effect]) ax.set_title(”Scatter Plot with Bold Outline”) plt.legend() plt.show() Output After executing the above code, we get the following output − Combined Path Effects Creating a combined path effects plot in Matplotlib allows us to apply multiple artistic enhancements to a line such as linestyle, markers, color gradients, and transparency. Linestyle − You can choose various linestyle options like solid lines (”-”), dashed lines (”–”), dotted lines (”:”), and more. Markers − Markers can be added to highlight specific data points. Common markers include circles (”o”), squares (”s”), triangles (”^”), etc. Color Gradients − You can use color gradients to create visually appealing lines. You can achieve this by specifying a “colormap” and using it to color the line based on a variable. Transparency − Adding transparency to the line can make overlapping lines more distinguishable. You can adjust transparency using the “alpha” parameter. Example Now, we are applying three path effects to the line: a subtle shadow effect, a bold black outline, and a slight blur effect. The result displays a line plot with a combination of these effects. import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects import numpy as np # Generating data x = np.linspace(0, 10, 100) y = np.sin(x) # Creating a line plot fig, ax = plt.subplots() line, = ax.plot(x, y, label=”Combined Effects Line”) # Combine multiple path effects: Shadow, Bold Outline, and Blur shadow_effect = path_effects.withStroke(linewidth=5, foreground=”cyan”) outline_effect = path_effects.withStroke(linewidth=3, foreground=”red”) blur_effect = path_effects.withStroke(linewidth=5, foreground=”magenta”, alpha=0.4) # Applying the combined effects to the line line.set_path_effects([shadow_effect, outline_effect, blur_effect]) ax.set_title(”Combined Path Effects Line”) plt.legend() plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Saving Figures

Matplotlib – Saving Figures ”; Previous Next Saving figures in Matplotlib library allows us to export our plots to various file formats such as PNG, PDF, SVG and so on to use those saved plots in various reports, presentations or publications. Matplotlib library provides the savefig() function for to save the plot that we have created. Common File Formats for Saving PNG (.png) − Good for general-purpose images which supports transparency. JPEG (.jpg) − Suitable for images with smooth gradients but may lose some quality due to compression. PDF (.pdf) − Ideal for vector-based images scalable without loss of quality. SVG (.svg) − Scalable Vector Graphics which suitable for web-based or vector-based graphics. Saving figures in Matplotlib library is useful for preserving visualizations in various formats by ensuring they can be shared, used or embedded in different contexts as needed. Adjusting the file format and resolution allows us to balance image quality and file size based on your requirements. Syntax The following is the syntax and parameters for using the savefig() method. plt.savefig(fname, dpi=None, bbox_inches=”tight”, pad_inches=0.1, format=None, kwargs) Where, fname − The file name or path of the file to save the figure. The file extension determines the file format such as “.png”, “.pdf”. dpi − Dots per inch i.e. resolution for the saved figure. Default is “None” which uses the Matplotlib default. bbox_inches − Specifies which part of the figure to save. Options include ”tight”, ”standard” or a specified bounding box in inches. pad_inches − Padding around the figure when bbox_inches=”tight”. format − Explicitly specify the file format. If ”None” the format is inferred from the file extension in fname. kwargs − Additional keyword arguments specific to the chosen file format. Saving the plot in specified location In this example we are creating a simple line plot by using the plot() function and then we are trying to save the plotted image in the specified location with the specified filename. Example import matplotlib.pyplot as plt # Data x = [22,1,7,2,21,11,14,5] y = [24,2,12,5,5,5,9,12] plt.plot(x,y) # Customize the plot (optional) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Simple Line Plot”) # Display the plot plt.savefig(”matplotlib/Savefig/lineplot.png”) plt.show() Output On executing the above code we will get the following output − Saving plot in .svg format Here, this is another example of saving the plotted plot by using the savefig() by specifying the file format as svg and dpi as 300 to set the resolution. Example import matplotlib.pyplot as plt # Data x = [22,1,7,2,21,11,14,5] y = [24,2,12,5,5,5,9,12] plt.plot(x,y) # Customize the plot (optional) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Simple Line Plot”) # Display the plot plt.savefig(”matplotlib/Savefig/lineplot2.svg”,dpi = 500) plt.show() Output On executing the above code we will get the following output − Note We should call savefig() before calling show() if we want to save the figure with the exact appearance shown on the screen otherwise empty file will be saved. The file extension in the fname parameter determines the format of the saved file. Matplotlib automatically infers the format if format is None. Print Page Previous Next Advertisements ”;

Matplotlib – Contour Plot

Matplotlib – Contour Plots ”; Previous Next A contour plot, also known as a contour map or a level plot, is a graphical representation of a three-dimensional surface on a two-dimensional plane. In a contour plot, the surface is represented by a series of contour lines. Each contour line connects points of equal value on the surface, showing regions where the function has the same value. These contour lines are drawn at constant intervals or “levels”, hence the name “level plot”. Imagine you have a contour plot of temperature across a map. Each contour line represents areas with the same temperature, like 50°F, 60°F, and so on. By looking at the plot, you can easily see where it is hotter or cooler across the map − Contour Plot in Matplotlib You can create contour plots in Matplotlib using the contour() function in the “matplotlib.pyplot” module. This function accepts X and Y coordinates as either 1D or 2D arrays, representing the grid on which the function “Z” is evaluated. “Z” is a 2D array containing the function values corresponding to the grid points defined by X and Y. Let”s start by drawing a basic contour plot. Basic Contour Plot A basic 3D contour in Matplotlib shows contour lines that connect points of equal value, representing the levels or “heights” of the data. Each contour line corresponds to a specific value, forming a map-like representation of the dataset. Example In the following example, we are create a basic contour plot. We define the x and y coordinates for the grid, and then use a mathematical function to generate the z values. With these x, y, and z values, we create a contour plot using the contour() function − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(-2, 2, 100) y = np.linspace(-2, 2, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X) * np.cos(Y) # Creating contour plot plt.contour(X, Y, Z) # Adding labels and title plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Basic Contour Plot”) # Displaying the plot plt.show() Output Following is the output of the above code − Filled Contour Plot In a filled contour plot in Matplotlib, instead of just showing contour lines, it fills in the areas between the lines with colors, creating a shaded representation of the data surface. Each color represents a different level or “height” of the data, allowing you to easily see the distribution within the dataset. Example In here, we create a filled contour plot using the contourf() function, which colors the regions between contour lines − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(-2, 2, 100) y = np.linspace(-2, 2, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X) * np.cos(Y) # Creating a filled contour plot plt.contourf(X, Y, Z) # Adding labels and title plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Filled Contour Plot”) # Displaying the plot plt.show() Output On executing the above code we will get the following output − Contour Plot with Specific Levels In a contour plot with specific levels, you specify the levels at which you want the contours to be drawn. Each contour line connects points of equal value, representing different levels or “heights” of the data. This allows you to customize the visualization to highlight specific features or intervals within the dataset. Example In this example, we customize the contour plot by specifying specific contour levels using Matplotlib. After generating the data and creating the contour plot, we use the levels parameter in the contour() function to define the contour levels − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(-2, 2, 100) y = np.linspace(-2, 2, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X) * np.cos(Y) # Defining contour levels levels = np.linspace(-1, 1, 20) # Creating contour plot with specific levels plt.contour(X, Y, Z, levels=levels) # Adding labels and title plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Contour Plot with Specific Levels”) # Displaying the plot plt.show() Output After executing the above code, we get the following output − Contour Plot with Colorbar In Matplotlib, a contour plot with a colorbar displays contour lines to show points of equal value in the dataset, and a colorbar alongside the plot to indicate the correspondence between colors and data values. The colorbar acts as a visual guide, helping you to understand the range and distribution of data values represented by different colors in the plot. Example Here, we create a contour plot with a colorbar using Matplotlib. After generating the data and creating the contour plot, we add a colorbar to the plot using the colorbar() function. This colorbar provides a visual representation of the z values corresponding to the contour plot − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(-2, 2, 100) y = np.linspace(-2, 2, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X) * np.cos(Y) # Creating a contour plot contour = plt.contour(X, Y, Z) # Adding colorbar plt.colorbar(contour, label=”Z-values”) # Adding labels and title plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Contour Plot with Colorbar”) # Displaying the plot plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;

Matplotlib – Anaconda distribution

Matplotlib – Anaconda Distribution ”; Previous Next Matplotlib library is a widely-used plotting library in Python and it is commonly included in the Anaconda distribution. What is Anaconda Distribution? Anaconda is a distribution of Python and other open-source packages that aims to simplify the process of setting up a Python environment for data science, machine learning and scientific computing. Anaconda distribution is available for installation at https://www.anaconda.com/download/. For installation on Windows, 32 and 64 bit binaries are available − Anaconda3-5.1.0-Windows-x86.exe Anaconda3-5.1.0-Windows-x86_64.exe Installation is a fairly straightforward wizard based process. You can choose between adding Anaconda in PATH variable and registering Anaconda as your default Python. For installation on Linux, download installers for 32 bit and 64 bit installers from the downloads page − Anaconda3-5.1.0-Linux-x86.sh Anaconda3-5.1.0-Linux-x86_64.sh Now, run the following command from the Linux terminal − Syntax $ bash Anaconda3-5.0.1-Linux-x86_64.sh Canopy and ActiveState are the most sought after choices for Windows, macOS and common Linux platforms. The Windows users can find an option in WinPython. Here is how Matplotlib is typically associated with the Anaconda distribution: Matplotlib in Anaconda Pre-Installed Matplotlib library is often included in the default installation of the Anaconda distribution. When we install Anaconda Matplotlib is available along with many other essential libraries for data visualization. Integration with Jupyter Anaconda comes with Jupyter Notebook which is a popular interactive computing environment. Matplotlib seamlessly integrates with Jupyter and makes our work easy to create and visualize plots within Jupyter Notebooks. Anaconda Navigator Anaconda Navigator is a graphical user interface that comes with the Anaconda distribution. This allows users to manage environments, install packages and launch applications. It provides an easy way to access and launch Jupyter Notebooks for Matplotlib plotting. Conda Package Manager Anaconda uses the ”conda” package manager which simplifies the installation, updating and managing of Python packages. We can use ”conda” to install or update Matplotlib within our Anaconda environment. Verifying Matplotlib Installation To verify whether Matplotlib is installed in our Anaconda environment we can use the following steps. Open the Anaconda Navigator. Navigate to the “Envinornments” tab. Look for “Matplotlib” in the list of installed packages. If it”s there Matplotlib is installed. Alternatively we can open Anaconda Prompt or a terminal and run the below mentioned code Syntax conda list matplotlib This command will list the installed version of Matplotlib in our current Anaconda environment. Output Installing or Updating Matplotlib in Anaconda If Matplotlib is not installed or we want to update it then we can use the following commands in the Anaconda Prompt or terminal. To install Matplotlib Syntax conda install matplotlib As the matplotlib is already installed in the system it’s shown the message the All requested packages already installed. To update Matplotlib Syntax conda update matplotlib The above mentioned commands will manage the installation or update of Matplotlib and its dependencies in our Anaconda environment. Finally we can say Matplotlib is a fundamental part of the Anaconda distribution making it convenient for users to create high-quality visualizations in their Python environments for data analysis and scientific computing. Print Page Previous Next Advertisements ”;

Matplotlib – Box Plot

Matplotlib – Box Plots ”; Previous Next A box plot represents the distribution of a dataset in a graph. It displays the summary statistics of a dataset, including the minimum, first quartile (Q1), median (Q2), third quartile (Q3), and maximum. The box represents the interquartile range (IQR) between the first and third quartiles, while whiskers extend from the box to the minimum and maximum values. Outliers, if present, may be displayed as individual points beyond the whiskers. Imagine you have the exam scores of students from three classes. A box plot is a way to show how these scores are spread out − Minimum and Maximum − The smallest and largest scores are shown as the ends of the plot. Quartiles (Q1, Q2, Q3) − The scores are split into four parts. The middle score is the median (Q2). The scores below the median are the first quartile (Q1), and those above are the third quartile (Q3). It helps you see where most of the scores lie. Interquartile Range (IQR) − The range between Q1 and Q3 is called the interquartile range. Box − The box in the middle represents the interquartile range. So, it is showing you where half of the scores are. Whiskers − Lines (whiskers) extend from the box to the smallest and largest scores, helping you see how spread out the scores are. Outliers − If there are any scores way above or below the rest, they might be shown as dots beyond the whiskers. These are like the standout scores. Box Plot in Matplotlib We can create a box plot in Matplotlib using the boxplot() function. This function allows us to customize the appearance of the box plot, such as changing the whisker length, adding notches, and specifying the display of outliers. The boxplot() Function The boxplot() function in Matplotlib takes one or more datasets as input and generates a box plot for each dataset. Following is the syntax of boxplot() function in Matplotlib − Syntax plt.boxplot(x, notch=None, patch_artist=None, widths=None, labels=None, …) Where, x is the dataset or a list of datasets for which the box plot is to be created. If notch (optional) is True, it creates a vertical box plot; if False, creates a horizontal box plot. If patch_artist (optional) is True, it fills the box with color. widths (optional) represents the width of the boxes. labels (optional) sets labels for each dataset, useful when plotting multiple box plots. These are just a few parameters; there are more optionals parameters available for customization. Horizontal Box Plot with Notches We can create a horizontal box plot with notches to display the distribution of a dataset in a horizontal orientation. It includes notches around the median lines, providing a visual estimate of the uncertainty around the median values. Example In the following example, we are creating a horizontal box plot with notches around the medians for three data sets, where each box represents a set of values along the y-axis categories − import matplotlib.pyplot as plt # Data data = [[1, 2, 3, 4, 5], [3, 6, 8, 10, 12], [5, 10, 15, 20, 25]] # Creating a horizontal box plot with notches plt.boxplot(data, vert=False, notch=True) plt.title(”Horizontal Box Plot with Notches”) plt.xlabel(”Values”) plt.ylabel(”Categories”) plt.show() Output After executing the above code, we get the following output − Box Plot with Custom Colors We can create a box plot with custom colors, graphically representing the data with different colors to fill the boxes. Each box represents the distribution of values within a category, and by adding a custom color, we introduce a stylistic touch that makes it easier to differentiate between categories. Example In here, we are enhancing the box plot by filling the boxes with a custom color i.e. skyblue − import matplotlib.pyplot as plt data = [[1, 2, 3, 4, 5], [3, 6, 8, 10, 12], [5, 10, 15, 20, 25]] # Creating a box plot with custom colors plt.boxplot(data, patch_artist=True, boxprops=dict(facecolor=”skyblue”)) plt.title(”Box Plot with Custom Colors”) plt.xlabel(”Categories”) plt.ylabel(”Values”) plt.show() Output Following is the output of the above code − Grouped Box Plot We can create a grouped box plot to compare the distributions of multiple groups side by side. Each group has its own set of boxes, where each box represents the distribution of values within that group. Example Now, we are creating a grouped box plot to compare the exam scores of students from three different classes (A, B, and C). Each box represents the distribution of scores within a class, allowing us to easily observe and compare the central tendencies, spreads, and potential outliers across the three classes − import matplotlib.pyplot as plt import numpy as np class_A_scores = [75, 80, 85, 90, 95] class_B_scores = [70, 75, 80, 85, 90] class_C_scores = [65, 70, 75, 80, 85] # Creating a grouped box plot plt.boxplot([class_A_scores, class_B_scores, class_C_scores], labels=[”Class A”, ”Class B”, ”Class C”]) plt.title(”Exam Scores by Class”) plt.xlabel(”Classes”) plt.ylabel(”Scores”) plt.show() Output On executing the above code we will get the following output − Box Plot with Outliers A box plot with outliers is a graphical representation of data that includes additional information about extreme values in the dataset. In a standard box plot, we represent outliers, data points significantly different from the majority, as individual points beyond the “whiskers” that extend from the box. This plot helps in identifying exceptional values that may have a significant impact on the overall distribution of the data. Example In the example below, we are creating a box plot that provides a visual representation of the sales distribution for each product, and the outliers highlight

Matplotlib – Jupyter Notebook

Matplotlib – Jupyter Notebook ”; Previous Next Jupyter is a loose acronym meaning Julia, Python, and R. These programming languages were the first target languages of the Jupyter application, but nowadays, the notebook technology also supports many other languages. In 2001, Fernando Pérez started developing Ipython. IPython is a command shell for interactive computing in multiple programming languages, originally developed for the Python. Matplotlib in Jupyter Notebook provides an interactive environment for creating visualizations right alongside our code. Let”s go through the steps to start using Matplotlib in a Jupyter Notebook. Matplotlib library in Jupyter Notebook provides a convenient way to visualize data interactively by allowing for an exploratory and explanatory workflow when working on data analysis, machine learning or any other Python-based project. Consider the following features provided by IPython − Interactive shells (terminal and Qt-based). A browser-based notebook with support for code, text, mathematical expressions, inline plots and other media. Support for interactive data visualization and use of GUI toolkits. Flexible, embeddable interpreters to load into one”s own projects. In 2014, Fernando Pérez announced a spin-off project from IPython called Project Jupyter. IPython will continue to exist as a Python shell and a kernel for Jupyter, while the notebook and other language-agnostic parts of IPython will move under the Jupyter name. Jupyter added support for Julia, R, Haskell and Ruby. Starting Jupyter Notebook The below are the steps to be done by one by one to work in the Jupyter Notebook. Launch Jupyter Notebook Open Anaconda Navigator. Launch Jupyter Notebook from the Navigator or in the terminal/Anaconda Prompt type jupyter notebook and hit Enter. Create or Open a Notebook Once Jupyter Notebook opens in our web browser then navigate to the directory where we want to work. After click on “New” and choose a Python notebook which is often referred to as an “Untitled” notebook. Import Matplotlib In a Jupyter Notebook cell import Matplotlib library by using the lines of code. import matplotlib.pyplot as plt %matplotlib inline %matplotlib inline is a magic command that tells Jupyter Notebook to display Matplotlib plots inline within the notebook. Create Plots We can now use Matplotlib functions to create our plots. For example let’s create a line plot by using the numpy data. Example import numpy as np import matplotlib.pyplot as plt # Generating sample data x = np.linspace(0, 20, 200) y = np.sin(x) # Plotting the data plt.figure(figsize=(8, 4)) plt.plot(x, y, label=”sin(x)”) plt.title(”Sine Wave”) plt.xlabel(”x”) plt.ylabel(”sin(x)”) plt.legend() plt.grid(True) plt.show() Output Interact with Plots Once the plot is generated then it will be displayed directly in the notebook below the cell. We can interact with the plot i.e. panning, zooming can be done if we used %matplotlib notebook instead of %matplotlib inline at the import stage. Multiple Plots We can create multiple plots by creating new cells and running more Matplotlib commands. Markdown Cells We can add explanatory text in Markdown cells above or between code cells to describe our plots or analysis. Saving Plots We can use plt.savefig(”filename.png”) to save a plot as an image file within our Jupyter environment. Closing Jupyter Notebook Once we have finished working in the notebook we can shut it down from the Jupyter Notebook interface or close the terminal/Anaconda Prompt where Jupyter Notebook was launched. Hide Matplotlib descriptions in Jupyter notebook To hide matplotlib descriptions of an instance while calling plot() method, we can take the following steps Open Ipython instance. import numpy as np from matplotlib, import pyplot as plt Create points for x, i.e., np.linspace(1, 10, 1000) Now, plot the line using plot() method. To hide the instance, use plt.plot(x); i.e., (with semi-colon) Or, use _ = plt.plot(x) Example In this example we are hiding the description code. import numpy as np from matplotlib import pyplot as plt x = np.linspace(1, 10, 1000) plt.plot(x) plt.show() Output [<matplotlib.lines.Line2D at 0x1f6d31d9130>] Print Page Previous Next Advertisements ”;

Matplotlib – Discussion

Discuss Matplotlib ”; Previous Next Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. It provides an object-oriented API that helps in embedding plots in applications using Python GUI toolkits such as PyQt, WxPythonotTkinter. It can be used in Python and IPython shells, Jupyter notebook and web application servers also. Print Page Previous Next Advertisements ”;