Matplotlib – Violin Plot ”; Previous Next Violin plots are similar to box plots, except that they also show the probability density of the data at different values. These plots include a marker for the median of the data and a box indicating the interquartile range, as in the standard box plots. Overlaid on this box plot is a kernel density estimation. Like box plots, violin plots are used to represent comparison of a variable distribution (or sample distribution) across different “categories”. A violin plot is more informative than a plain box plot. In fact while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data. import matplotlib.pyplot as plt import numpy as np np.random.seed(10) collectn_1 = np.random.normal(100, 10, 200) collectn_2 = np.random.normal(80, 30, 200) collectn_3 = np.random.normal(90, 20, 200) collectn_4 = np.random.normal(70, 25, 200) ## combine these different collections into a list data_to_plot = [collectn_1, collectn_2, collectn_3, collectn_4] # Create a figure instance fig = plt.figure() # Create an axes instance ax = fig.add_axes([0,0,1,1]) # Create the boxplot bp = ax.violinplot(data_to_plot) plt.show() Print Page Previous Next Advertisements ”;
Category: matplotlib
Matplotlib – Useful Resources ”; Previous Next The following resources contain additional information on Matplotlib. Please use them to get more in-depth knowledge on this. Useful Video Courses Python Data Science Course With Numpy, Pandas, and Matplotlib Best Seller 64 Lectures 6 hours Abhilash Nelson More Detail Data Visualization using MatPlotLib & Seaborn 12 Lectures 4 hours DATAhill Solutions Srinivas Reddy More Detail Matplotlib Full Python Course 10 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy More Detail Comprehensive Data Visualization Course: With Matplotlib in Python 33 Lectures 4 hours Aipython More Detail Basics Data Science with Numpy, Pandas and Matplotlib 11 Lectures 2.5 hours Akbar Khan More Detail Pandas Crash Course for beginners : NumPy + Pandas + Matplotlib Most Popular 63 Lectures 6 hours Anmol Tomar More Detail Print Page Previous Next Advertisements ”;
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 – PostScript
Matplotlib – PostScript ”; Previous Next PostScript is a page description language and a dynamically typed, stack-based programming language often abbreviated as PS. Created by Adobe Systems in the early 1980s, its primary purpose is to describe the layout and graphics of printed pages. It is widely used in electronic publishing and desktop publishing applications. A PostScript file can be printed or displayed on different devices without losing quality. This is the key advantage when generating plots for different purposes. PostScript in Matplotlib In the context of Matplotlib, PostScript serves as a backend rendering engine (used for displaying figures on the screen or writing to files), enabling users to generate publication-quality plots and graphics. When you choose the PostScript backend, Matplotlib generates PostScript code to describe the layout and appearance of the plot. The PostScript code generated by Matplotlib includes instructions for drawing lines, shapes, text, and other graphical elements on a page. These instructions are written in the PostScript programming language. The Matplotlib PostScript Backend (matplotlib.backends.backend_ps) can produce both .ps and .eps files. Create a PostScript file Let”s explore how to create a simple plot and save it as a PostScript file using Matplotlib. Example 1 This example demonstrates how to create a simple plot with wrapped text and saves it as a PostScript file(.ps). import matplotlib import matplotlib.pyplot as plt import textwrap from pylab import * # Generate a string containing printable characters (ASCII 32 to 126) text_to_wrap = “”.join(c for c in map(chr, range(32, 127)) if c.isprintable()) # Wrap the string to fit within the figure wrapped_text = “n”.join(textwrap.wrap(text_to_wrap)) # Add the wrapped text to the figure figtext(0, 0.5, wrapped_text) # Save the figure to a PostScript file named “test.ps” savefig(“test.ps”) print(”Successfully created the PostScript (PS) file…”) Output If you visit the folder where the Output is saved you can observe resultant PostScript file named test.ps. Successfully created the PostScript (PS) file… Example 2 Here is another example that demonstrates how to use the PostScript backend to generate a plot and save it to an encapsulated PostScript (EPS) file. import numpy as np from matplotlib import pyplot as plt # Generate data x_data = np.linspace(1, 10, 100) y_data = np.sin(x_data) # Create the plot plt.plot(x_data, y_data, c=”green”, marker=”o”) plt.grid() # Save the figure to a PostScript file named “example.eps” plt.savefig(“example.eps”) print(”Successfully created the encapsulated PostScript (EPS) file…”) Output If you visit the folder where the Output is saved you can observe resultant PostScript file named example.eps. Successfully created the encapsulated PostScript (EPS) file… Customizing PostScript Output Adjusting the PostScript output settings in Matplotlib allows you to enhance the visual quality of Encapsulated PostScript (EPS) files. By default, Matplotlib uses a distillation process when creating EPS files. This distillation step removes specific PostScript operators that LaTeX considers illegal in an EPS file. One effective workaround involves modifying the resolution parameter to achieve better visual results. The rcParams[“ps.distiller.res”] parameter controls the resolution of the EPS files, with the default value set to 6000. Increasing this value can result in larger files but may significantly improve visual quality and maintain reasonable scalability. Example 1 This example demonstrates how adjusting resolution parameter can enhance the visual quality of EPS files. import numpy as np import matplotlib.pyplot as plt # Set the resolution for EPS files plt.rcParams[“ps.distiller.res”] = 12000 # Set the figure size and enable autolayout plt.rcParams[“figure.figsize”] = [7, 3.50] plt.rcParams[“figure.autolayout”] = True # Generate data x_data = np.linspace(1, 10, 100) y_data = np.sin(x_data) # Plotting plt.plot(x_data, y_data, label=”Sine Wave”, color=”green”) # Save the figure as an EPS file plt.savefig(”Output customized file.eps”, format=”eps”, bbox_inches=”tight”) print(”Successfully created the output customized PostScript (EPS) file…”) Output If you visit the folder where the Output is saved you can observe resultant PostScript file named Output customized file.eps. Successfully created the output customized PostScript (EPS) file… Example 2 Here is an example that demonstrates how the transparency is preserved when saving the plot as an .eps file by setting the transparent=True parameter in the savefig() function. import numpy as np import matplotlib.pyplot as plt # Adjust figure size and autolayout plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True # Generate data x_data = np.linspace(1, 10, 100) y_data = np.sin(x_data) # Plot data with transparency plt.plot(x_data, y_data, c=”green”, marker=”o”, alpha=.35, ms=10, lw=1) plt.grid() # Save plot as .eps by preserving the transparency plt.savefig(“lost_transparency_img.eps”, transparent=True) # Display plot plt.show() Output On executing the above code you will get the following output − Whenever plots are saved in .eps/.ps, then the transparency of the plots get lost. You can observe the difference in th eabove image. Print Page Previous Next Advertisements ”;
Matplotlib – Ribbon Box
Matplotlib – Ribbon Box ”; Previous Next In general, a “ribbon box” is a graphical representation used to visualize data distributions across different categories or groups. The term “ribbon box” refers to a specific type of plot that displays these distributions in a visually appealing and informative manner. It is particularly useful when you have multiple categories or groups and want to compare the distributions of a variable across these categories. In a ribbon box plot − Each category or group is typically represented along the x-axis. The y-axis often represents the range or distribution of a numeric variable. Each “ribbon” corresponds to the distribution of the numeric variable within a particular category or group. The ribbon can be shaded or colored to indicate the density or intensity of the distribution within each category. This allows for easy comparison of distributions across different categories. Here, we created a simple ribbon box plot with three categories (Category 1, Category 2, Category 3) along the x-axis and their corresponding distribution of values along the y-axis. We shade the ribbon boxes to indicate the intensity of the distribution within each category. Ribbon Box in Matplotlib In Matplotlib, a “ribbon box” is a visual representation used to display the distribution of a numeric variable across different categories or groups. While matplotlib does not have a specific function to create ribbon box plots, you can use other techniques available, such as − Use matplotlib”s plot() function to plot the central line for each category or group. This line represents the central tendency of the data within each category, such as the mean or median. Using the fill_between function to fill the area between two curves, where one curve represents the upper boundary of the ribbon and the other curve represents the lower boundary. Customize the appearance of the plot as needed by adding labels, titles, legends, gridlines, etc. Ribbon Box Plot with Confidence Interval In matplotlib, a simple ribbon box plot with confidence interval is a graphical representation used to display the central tendency of a dataset along with the uncertainty around that central value. It is like plotting the average of something (like daily temperatures) and shading an area around it to show how much the actual values might vary due to uncertainty. Example In the following example, we are creating a ribbon box plot showing the central tendency and confidence interval (uncertainity) around a sine wave, using matplotlib”s plot() and fill_between() functions, respectively − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y_mean = np.sin(x) # Standard deviation y_std = 0.1 # Plotting the central line plt.plot(x, y_mean, color=”blue”, label=”Mean”) # Plotting the shaded area representing the uncertainty (confidence interval) plt.fill_between(x, y_mean – y_std, y_mean + y_std, color=”blue”, alpha=0.2, label=”Uncertainty”) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Simple Ribbon Box Plot with Confidence Interval”) plt.legend() plt.grid(True) plt.show() Output Following is the output of the above code − Multiple Ribbon Box Plots In Matplotlib, multiple ribbon box plots are a way to compare the distributions of multiple datasets using ribbon box plots within the same plot. Each ribbon box plot represents the spread and central tendency of a different dataset, allowing for easy comparison between them. Example In here, we are generating multiple ribbon box plots with different colors to represent two sine and cosine waves along with their uncertainty bands using matplotlib − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y_means = [np.sin(x), np.cos(x)] # Standard deviations y_stds = [0.1, 0.15] colors = [”blue”, ”green”] # Plotting multiple ribbon box plots with different colors for y_mean, y_std, color in zip(y_means, y_stds, colors): plt.plot(x, y_mean, color=color, label=”Mean”, alpha=0.7) plt.fill_between(x, y_mean – y_std, y_mean + y_std, color=color, alpha=0.2) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Multiple Ribbon Box Plots with Different Colors”) plt.legend() plt.grid(True) plt.show() Output On executing the above code we will get the following output − Stacked Ribbon Box Plot In Matplotlib, stacked ribbon box plots are a type of graphical representation used to compare the distributions of multiple datasets while also showing the combined distribution of all the datasets. In a stacked ribbon box plot, each dataset is represented by its own ribbon box plot, just like in multiple ribbon box plots. However, instead of displaying the box plots side by side, they are stacked vertically on top of each other. This stacking allows for a direct comparison of the distributions of each dataset while also showing how they contribute to the overall distribution when combined. Example Now, we are plotting a stacked ribbon box plot, stacking the distributions of a sine and cosine wave to compare their variations across the x-axis using matplotlib − import matplotlib.pyplot as plt import numpy as np # Generating example data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Plotting stacked ribbon box plot plt.plot(x, y1, color=”blue”, label=”Dataset 1”) plt.fill_between(x, y1, color=”blue”, alpha=0.2) plt.plot(x, y2, color=”green”, label=”Dataset 2”) plt.fill_between(x, y2, color=”green”, alpha=0.2) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Stacked Ribbon Box Plot”) plt.legend() plt.grid(True) plt.show() Output After executing the above code, we get the following output − Horizontal Ribbon Box Plot A horizontal ribbon box plot in Matplotlib is a graphical representation that shows the distribution of a dataset along a horizontal axis using ribbon-shaped boxes. In a horizontal ribbon box plot, the dataset”s values are grouped into categories or bins, and for each category, a ribbon-shaped box is drawn horizontally. The length of each box represents the range of values within that category, while the position along the horizontal axis indicates the category itself. Example In the following example,
Matplotlib – Ellipse with Units ”; Previous Next An ellipse is a geometric shape that looks like a stretched circle. It is defined by two key properties: its major axis (the longest diameter) and its minor axis (the shortest diameter). These axes intersect at the center of the ellipse, and the shape of an ellipse is determined by the lengths of these axes. Both the distance from the center to the edge along the major axis and the distance from the center to the edge along the minor axis are important. In terms of units, you would measure these distances using some kind of unit, like inches, centimeters, or any other measurement you choose. So, when we say an ellipse with units, we mean that we are using specific measurements (units) to describe the size of the ellipse, considering both the length of the major axis and the length of the minor axis. Ellipse with Units in Matplotlib We can create an ellipse with units in Matplotlib using the “Ellipse” class in the “matplotlib.patches” module. The Ellipse class allows you to define the center, width and height (major and minor axes), angle of rotation, and other properties of the ellipse such as its rotation angle. The units of measurement for the axes depend on the coordinate system you are using. For example, if you are working with a plot in inches, the major and minor axes lengths would be in inches. Fixed Size Ellipse in Data Coordinates In Matplotlib, creating a fixed size ellipse in data coordinates involves drawing an ellipse on a plot with a specific size and position determined by data coordinates. This means that the dimensions of the ellipse are specified in the same units as your actual data. For instance, if you have a dataset with x and y values, you can draw an ellipse where the center is located at a particular (x, y) point, and the width and height of the ellipse are defined in terms of the data coordinates. Example we are drawing a simple ellipse with a fixed size specified in data coordinates. The center of the ellipse is located at (3, 5) on the plot, and the width is set to “4” units in meters, while the height is set to “2” units − import matplotlib.pyplot as plt from matplotlib.patches import Ellipse # Creating a plot fig, ax = plt.subplots() # Ellipse in data coordinates (units: meters) ellipse = Ellipse((3, 5), width=4, height=2, edgecolor=”b”, facecolor=”none”) ax.add_patch(ellipse) # Setting plot title and labels ax.set_title(”Fixed Size Ellipse in Data Coordinates”) ax.set_xlabel(”X-axis (meters)”) ax.set_ylabel(”Y-axis (meters)”) # Setting aspect ratio to ”equal” ax.set_aspect(”equal”) # Adjusting axis limits ax.set_xlim(0, 6) ax.set_ylim(3, 7) # Displaying dimensions plt.text(3, 5, f”Width: 4 metersnHeight: 2 meters”, ha=”center”, va=”center”, color=”red”, fontsize=10) plt.show() Output Following is the output of the above code − Ellipse with Variable Size in Axes Coordinates Creating an ellipse with variable size in axes coordinates in Matplotlib involves drawing an ellipse on a plot where the dimensions are specified in terms of the axes, rather than the actual data. In other words, the width and height of the ellipse are given as a percentage of the total length of the x and y axes, respectively. For example, if you want to visualize an ellipse that always covers 60% of the x-axis and 30% of the y-axis, regardless of the specific data values, you can use axes coordinates. This is particularly useful when you want the size of the ellipse to be relative to the overall dimensions of the plot. Example In here, we are drawing a an ellipse with a variable size specified in axes coordinates. The center of the ellipse is placed at (0.5, 0.5), which corresponds to the center of the plot. The width and height are set to 60% and 30% of the respective axis lengths, allowing the ellipse to scale with changes in the axes − import matplotlib.pyplot as plt from matplotlib.patches import Ellipse # Creating a plot fig, ax = plt.subplots() # Ellipse in axes coordinates ellipse = Ellipse((0.5, 0.5), width=0.6, height=0.3, edgecolor=”r”, facecolor=”none”, transform=ax.transAxes) ax.add_patch(ellipse) # Setting plot title and labels ax.set_title(”Ellipse with Variable Size in Axes Coordinates”) ax.set_xlabel(”X-axis (normalized)”) ax.set_ylabel(”Y-axis (normalized)”) # Displaying dimensions in the output plt.text(0.5, 0.5, f”Width: 0.6 (normalized)nHeight: 0.3 (normalized)”, ha=”center”, va=”center”, color=”blue”, fontsize=10, transform=ax.transAxes) plt.show() Output On executing the above code we will get the following output − Ellipse Centered at Figure Origin Creating an ellipse centered at figure origin in Matplotlib involves drawing an ellipse on a plot with its center positioned at the origin of the entire figure. The origin is the point (0, 0) in the coordinate system of the figure. In this case, the width and height of the ellipse are specified in the units of the figure, and the center of the ellipse is precisely at the origin. This demonstrates how to position an ellipse with respect to the overall figure rather than the individual axes. Example In the example below, we are creating an ellipse with its center at the origin of the figure (0, 0). The width is set to 4 units, and the height is set to 2 units − import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import numpy as np # Creating a plot fig, ax = plt.subplots() # Ellipse centered at figure origin ellipse = Ellipse((0, 0), width=4, height=2, edgecolor=”g”, facecolor=”none”, transform=ax.transData) ax.add_patch(ellipse) # Marking the center with a marker center_x, center_y = 0, 0 ax.plot(center_x, center_y, marker=”o”, markersize=8, color=”red”, label=”Center”) # Dotted line to represent the center ax.plot([center_x, center_x], [center_y, center_y], ”r–”) # Horizontal and vertical lines passing through the center ax.axhline(center_y, color=”blue”, linestyle=”–”, label=”Horizontal Line”) ax.axvline(center_x, color=”purple”,
Matplotlib – Click Events
Matplotlib – Click Events ”; Previous Next In general, a click event occurs when a user interacts with a computer interface by pressing and releasing a mouse button or tapping on a touchscreen device. This event serves as a trigger for the computer system to recognize and respond to the user”s input. In the context of data visualization, like in Matplotlib or other plotting libraries, a click event can be used to capture specific user interactions with the plot, offering a dynamic and interactive experience. This could include tasks such as selecting data points, triggering updates or enabling user-initiated actions. Click Events in Matplotlib In Matplotlib, a click event occurs when a user interacts with a plot by clicking on the figure or a specific region within it. These events are associated with callback functions that are executed when the click happens. This can be done by connecting a callback function to the button_press_event using the mpl_connect() method on the figure canvas. Let”s see a basic example that demonstrates how a simple click event works. Example In this example, a click event is handled by the onclick function, which prints a message to the console when the user clicks anywhere on the plot. The figure contains a text element prompting the user to click. import numpy as np import matplotlib.pyplot as plt def onclick(event): print(”The Click Event Triggered!”) fig, ax = plt.subplots(figsize=(7, 4)) ax.text(0.1, 0.5, ”Click me anywhere on this plot!”, dict(size=20)) cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! Watch the video below to observe how the click event feature works here. Storing Click Event Coordinates Storing click event coordinates allows you to gather information about user interactions on a plot, facilitating tasks such as data point selection or analysis. Example Here is an example that stores and prints the coordinates of mouse clicks on the plot. This demonstrates how click events can be used to gather information about user interactions on a plot. import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 2*np.pi, 0.01) y = np.sin(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) clicked_coords = [] def onclick(event): global ix, iy ix, iy = event.xdata, event.ydata print(f”Clicked at x = {ix}, y = {iy}”) global clicked_coords clicked_coords.append((ix, iy)) # Disconnect the click event after collecting 5 coordinates if len(clicked_coords) == 5: fig.canvas.mpl_disconnect(cid) print(”Reached the maximum clicks…”) cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − Clicked at x = 0.0743760368663593, y = 0.11428680137603275 Clicked at x = 1.4368755760368663, y = 0.9928568371128363 Clicked at x = 3.130449769585254, y = 0.10714395555703438 Clicked at x = 4.7221548387096774, y = -1.014282838025715 Clicked at x = 6.377528110599078, y = 0.04285834318604875 Reached the maximum clicks… Watch the video below to observe how the click event feature works here. Click Event with Checkbox Integrating the checkbox widget with click events offers a dynamic way to control user interactions on the plots. By combining checkboxes with click events, you can enable or disable certain features, providing users with interactive control over the plot. Example In this example, a checkbox is used to control the adding text on the plot where the click event is triggered. import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons import numpy as np def onclick(event): # Only use events within the axes. if not event.inaxes == ax1: return # Check if Checkbox is “on” if check_box.get_status()[0]: ix, iy = event.xdata, event.ydata coords3.append((ix, iy)) # write text with coordinats where clicks occur if len(coords3) >= 1: ax1.annotate(f”* {ix:.1f}, {iy:.1f}”, xy=(ix, iy), color=”green”) fig.canvas.draw_idle() # Disconnect after 6 clicks if len(coords3) >= 6: fig.canvas.mpl_disconnect(cid) print(”Reached the maximum clicks…”) plt.close(fig) x = np.arange(0, 2*np.pi, 0.01) y = np.sin(2*x) fig, ax1 = plt.subplots(figsize=(7, 4)) ax1.plot(x, y) ax1.set_title(”This is my plot”) ax2 = plt.axes([0.7, 0.05, 0.1, 0.075]) check_box = CheckButtons(ax2, [”On”,], [False,], check_props={”color”:”red”, ”linewidth”:1}) coords3 = [] cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − Reached the maximum clicks… Watch the video below to observe how the click event feature works here. Print Page Previous Next Advertisements ”;
Matplotlib – Histogram
Matplotlib – Histogram ”; Previous Next A histogram is like a visual summary that shows how often different values appear in a set of data. Imagine you have a collection of numbers, like ages of people. A histogram divides these numbers into groups, called “bins,” and then uses bars to represent how many numbers fall into each bin. The taller the bar, the more numbers are in that group. Histogram in Matplotlib We can create a histogram in Matplotlib using the hist() function. This function allows us to customize various aspects of the histogram, such as the number of bins, color, and transparency. Histogram in Matplotlib is used to represent the distribution of numerical data, helping you to identify patterns. The hist() Function The hist() function in Matplotlib takes a dataset as input and divides it into intervals (bins). It then displays the frequency (count) of data points falling within each bin as a bar graph. Following is the syntax of hist() function in Matplotlib − Syntax plt.hist(x, bins=None, range=None, density=False, cumulative=False, color=None, edgecolor=None, …) Where, x is the input data for which the histogram is determined. bins (optional) is the number of bins or the bin edges. range (optional) is the lower and upper range of the bins. Default is the minimum and maximum of x If density (optional) is True, the histogram represents a probability density function. Default is False. If cumulative (optional) is True, a cumulative histogram is computed. Default is False. These are just a few parameters; there are more optionals parameters available for customization. Creating a Vertical Histogram In Matplotlib, creating a vertical histogram involves plotting a graphical representation of the frequency distribution of a dataset, with the bars oriented vertically along the y-axis. Each bar represents the frequency or count of data points falling within a particular interval or bin along the x-axis. Example In the following example, we are creating a vertical histogram by setting the “orientation” parameter to “vertical” within the hist() function − import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = [1, 2, 3, 1, 2, 3, 4, 1, 3, 4, 5] plt.hist(x, orientation=”vertical”) plt.show() Output We get the output as shown below − Customized Histogram with Density When we create a histogram with density, we are providing a visual summary of how data is distributed. We use this graph to see how likely different numbers are occurring, and the density option makes sure the total area under the histogram is normalized to one. Example In the following example, we are visualizing random data as a histogram with 30 bins, displaying it in green with a black edge. We are using the density=True parameter to represent the probability density − import matplotlib.pyplot as plt import numpy as np # Generate random data data = np.random.randn(1000) # Create a histogram with density and custom color plt.hist(data, bins=30, density=True, color=”green”, edgecolor=”black”, alpha=0.7) plt.xlabel(”Values”) plt.ylabel(”Probability Density”) plt.title(”Customized Histogram with Density”) plt.show() Output After executing the above code, we get the following output − Cumulative Histogram When we create a cumulative histogram, we graphically represent the total number of occurrences of values up to a certain point. It shows how many data points fall below or equal to a certain value. Example In here, we are using a histogram where each bar represents a range of exam scores, and the height of the bar tells us how many students, in total, scored within that range. By setting the cumulative=True parameter in the hist() function, we make sure that the histogram shows the cumulative progression of scores − import matplotlib.pyplot as plt import numpy as np # Generate random exam scores (out of 100) exam_scores = np.random.randint(0, 100, 150) # Create a cumulative histogram plt.hist(exam_scores, bins=20, cumulative=True, color=”orange”, edgecolor=”black”, alpha=0.7) plt.xlabel(”Exam Scores”) plt.ylabel(”Cumulative Number of Students”) plt.title(”Cumulative Histogram of Exam Scores”) plt.show() Output Following is the output of the above code − Histogram with Different Color and Edge Color When creating a histogram, we can customize the fill color and edge color, adding a visual touch to represent the data distribution. By doing this, we blend the histogram with a stylish and distinctive appearance. Example Now, we are generating a histogram for random data with 25 bins, and we are presenting it in purple color with blue edges − import matplotlib.pyplot as plt import numpy as np data = np.random.randn(1000) # Creating a histogram with different color and edge color plt.hist(data, bins=25, color=”purple”, edgecolor=”blue”) plt.xlabel(”Values”) plt.ylabel(”Frequency”) plt.title(”Histogram with Different Color and Edge Color”) plt.show() Output On executing the above code we will get the following output − Example To plot a histogram with colors, we can also extract colors from the “cm” parameter in the setp() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True data = np.random.random(1000) n, bins, patches = plt.hist(data, bins=25, density=True, color=”red”, rwidth=0.75) col = (n-n.min())/(n.max()-n.min()) cm = plt.cm.get_cmap(”RdYlBu”) for c, p in zip(col, patches): plt.setp(p, ”facecolor”, cm(c)) plt.show() Output On executing the above code we will get the following output − Example In here, we are specifying different colors for different bars in a matplotlib histogram by iterating in the range of number of bins and setting random facecolor for each bar − import numpy as np import matplotlib.pyplot as plt import random import string # Set the figure size plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True # Figure and set of subplots fig, ax = plt.subplots() # Random data data = np.random.rand(100) # Plot