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 ”;

Matplotlib – Quiver Plot

Matplotlib – Quiver Plot ”; Previous Next A quiver plot displays the velocity vectors as arrows with components (u,v) at the points (x,y). quiver(x,y,u,v) The above command plots vectors as arrows at the coordinates specified in each corresponding pair of elements in x and y. Parameters The following table lists down the different parameters for the Quiver plot − x 1D or 2D array, sequence. The x coordinates of the arrow locations y 1D or 2D array, sequence. The y coordinates of the arrow locations u 1D or 2D array, sequence. The x components of the arrow vectors v 1D or 2D array, sequence. The y components of the arrow vectors c 1D or 2D array, sequence. The arrow colors The following code draws a simple quiver plot − import matplotlib.pyplot as plt import numpy as np x,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25)) z = x*np.exp(-x**2 – y**2) v, u = np.gradient(z, .2, .2) fig, ax = plt.subplots() q = ax.quiver(x,y,u,v) plt.show() Print Page Previous Next Advertisements ”;

Matplotlib – Scroll Event

Matplotlib – Scroll Event ”; Previous Next In general, a scroll event occurs when a user interacts with the mouse scroll wheel. The scroll wheel that is located in the middle of the mouse is used to scroll up and down on any page without using the vertical scroll bar on the right hand side of a document or webpage. In this tutorial, we will explore about the scroll event handling in Matplotlib. Scroll event in Matplotlib Matplotlib provides a mechanism for handling the scroll events through MouseEvent class. This scroll_event event is triggered when a user rolled the mouse scroll wheel. Which is used for providing a mechanism for interactive navigation or zooming within plots. Example Here is a simple example that detects scroll events and displays the messages based on whether the user scrolls up or down the mouse scroll wheel. import matplotlib.pyplot as plt import numpy as np def on_scroll(event): if event.button == ”up”: print(”Scroll Up Event Triggered..”) elif event.button == ”down”: print(”Scroll Down Event Triggered..”) # Create a figure and axis fig, ax = plt.subplots() ax.text(0.13, 0.5, ”Scroll Mouse Wheel on me!”, dict(size=20)) # Connect the on_scroll method to the scroll_event fig.canvas.mpl_connect(”scroll_event”, on_scroll) plt.show() Output On executing the above code we will get the following output − Scroll Up Event Triggered.. Scroll Up Event Triggered.. Scroll Down Event Triggered.. Scroll Up Event Triggered.. Scroll Down Event Triggered.. Scroll Up Event Triggered.. Scroll Up Event Triggered.. Watch the video below to observe how the this scroll event feature works here. Zooming with Scroll Event Scroll events in Matplotlib can be used for dynamically zooming the plots. By connecting the scroll event to a callable function, users can dynamically adjust the view within a plot. Example Let”s see an example that demonestrates how to implement zoom functionality using the scroll event. import matplotlib.pyplot as plt def zoom_factory(axs, base_scale=2.): def zoom_fun(event): # get the current x and y limits cur_xlim = axs.get_xlim() cur_ylim = axs.get_ylim() cur_xrange = (cur_xlim[1] – cur_xlim[0]) * 0.2 cur_yrange = (cur_ylim[1] – cur_ylim[0]) * 0.2 # get event x location xdata = event.xdata ydata = event.ydata if event.button == ”up”: # deal with zoom in scale_factor = 1/base_scale elif event.button == ”down”: # deal with zoom out scale_factor = base_scale else: # deal with something that should never happen scale_factor = 1 print(event.button) # set new limits axs.set_xlim([xdata – cur_xrange*scale_factor, xdata + cur_xrange*scale_factor]) axs.set_ylim([ydata – cur_yrange*scale_factor, ydata + cur_yrange*scale_factor]) # force re-draw plt.draw() # get the figure of interest fig = axs.get_figure() # Connect the call back function to the scroll_event fig.canvas.mpl_connect(”scroll_event”, zoom_fun) # return the function return zoom_fun # Example Usage fig, axs = plt.subplots(figsize=(7, 4)) axs.plot(range(100)) scale = 1.5 f = zoom_factory(axs, base_scale=scale) plt.show() Output On executing the above program you will get the following figure roll the mouse scroll wheel to observe the Zooming effect in this plot − Watch the video below to observe how the this scroll event feature works here. Interactive Scrolling through Images The scroll event in Matplotlib can also be applied to interactively scroll through a series of images. This feature is particularly useful when navigating through multi-dimensional datasets or a collection of images. Example This example, creates a class IndexTracker to navigate through a series of 2D slices using the scroll event. The on_scroll method adjusts the index based on the scroll direction, then it updates and displayed image. import matplotlib.pyplot as plt import numpy as np class IndexTracker: def __init__(self, axs, X): self.index = 0 self.X = X self.axs = axs self.im = axs.imshow(self.X[:, :, self.index]) self.update() def on_scrolling(self, event): print(event.button, event.step) increment = 1 if event.button == ”up” else -1 maxs_index = self.X.shape[-1] – 1 self.index = np.clip(self.index + increment, 0, maxs_index) self.update() def update(self): self.im.set_data(self.X[:, :, self.index]) self.axs.set_title( f”Use scroll wheel to navigatenindex {self.index}”) self.im.axes.figure.canvas.draw() # 3D data x, y, z = np.ogrid[-25:25:100j, -25:25:100j, 1:50:100j] X = np.sin(x * y * z) / (x * y * z) # Create a figure fig, axs = plt.subplots() tracker = IndexTracker(axs, X) fig.canvas.mpl_connect(”scroll_event”, tracker.on_scrolling) plt.show() Output On executing the above program you will get the following figure roll the mouse scroll wheel to observe working of this example − up 1.0 up 2.0 down -1.0 down -2.0 down -1.0 up 1.0 up 1.0 down -1.0 down -1.0 up 1.0 up 3.0 down -1.0 down -3.0 Watch the video below to observe how the this scroll event feature works here. Print Page Previous Next Advertisements ”;

Matplotlib – Manual Contour

Matplotlib – Manual Contour ”; Previous Next Manual contouring in general refers to the process of outlining the boundaries of an object or a specific area by hand rather than relying on automated methods. This is usually done to create accurate representations of the shapes and boundaries within the image. A contour line represents a constant value on a map or a graph. It is like drawing a line to connect points that share the same height on a topographic map or lines on a weather map connecting places with the same temperature. Manual Contour in Matplotlib In Matplotlib, a manual contour plot is a way to represent three-dimensional data on a two-dimensional surface using contour lines. These lines connect points of equal value in a dataset, creating a map-like visualization of continuous data. For a manual contour plot, you specify the contour levels or values at which the lines should be drawn. The plot then displays these contour lines, with each line representing a specific value in the dataset. Basic Manual Contour Plot Creating a basic manual contours in Matplotlib involves drawing lines to connect points with the same value, forming closed loops or curves that represent distinct levels of the measured quantity. This process allows for customization and fine-tuning of the contour lines to accurately represent the given data. While manual contouring can be time-consuming, it provides a level of control and precision that may be necessary in certain situations where automated methods may not be adequate. Example In the following example, we are creating a simple contour plot using Matplotlib. We are using the contour() function to generate contour lines of a sine function, with manually specified levels, overlaying them on the XY-plane − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(-3, 3, 100) y = np.linspace(-3, 3, 100) # Creating a grid of x and y values X, Y = np.meshgrid(x, y) # Calculating the value of Z using the given function Z = np.sin(X**2 + Y**2) # Creating contour plot with manual levels levels = [-0.9, -0.6, -0.3, 0, 0.3, 0.6, 0.9] plt.contour(X, Y, Z, levels=levels) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Manual Contour Plot”) # Displaying the plot plt.show() Output Following is the output of the above code − Manual Contour Plot with Labeling In Matplotlib, a manual contour plot with labeling represents three-dimensional data on a two-dimensional surface with contour lines, and annotate specific contour levels with labels. This type of plot displays contour lines to show regions of equal data value, and adds text labels to these lines to indicate the corresponding data values. The labels help to identify important features or values in the dataset, making it easier to interpret the plot and understand the distribution of the data. Example In here, we are creating a contour plot with inline labels to the contour lines using the clabel() function − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(-3, 3, 100) y = np.linspace(-3, 3, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X**2 + Y**2) # Contour plot with labels levels = [-0.9, -0.6, -0.3, 0, 0.3, 0.6, 0.9] CS = plt.contour(X, Y, Z, levels=levels) plt.clabel(CS, inline=True, fontsize=12) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Manual Contour Plot with Labeling”) plt.show() Output On executing the above code we will get the following output − Manual Contour Plot with Filled Regions In Matplotlib, a manual contour plot with filled regions use colors to visually represent different levels or values in the dataset, unlike traditional contour plots that only show contour lines. Each filled region corresponds to a specific range of values, with colors indicating the intensity or magnitude of those values. Example In the example below, we are creating a filled contour plot of a sine function using the contourf() function with the “RdYlBu” colormap. We then add a color bar to indicate the intensity scale of the filled contours − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(-3, 3, 100) y = np.linspace(-3, 3, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X**2 + Y**2) # Creating contour plot with filled regions plt.contourf(X, Y, Z, levels=[-0.9, -0.6, -0.3, 0, 0.3, 0.6, 0.9], cmap=”RdYlBu”) plt.colorbar() plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Manual Contour Plot with Filled Regions”) plt.show() Output After executing the above code, we get the following output − Manual Contour Plot with Custom Line Styles In Matplotlib, a manual contour plot with custom line styles is a way to represent contour lines, where each line can have a distinct visual style. Generally, contour lines are drawn as solid lines, but with custom line styles, you can modify aspects like the line width, color, and pattern to distinguish different levels or values in the dataset. For example, you might use dashed lines, dotted lines, or thicker lines to highlight specific contour levels or regions of interest. Example Now, we are creating a manual contour plot with custom line styles by specifying a list of line styles to use for different levels. We achieve this by passing the “linestyles” parameter to the contour() function − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(-3, 3, 100) y = np.linspace(-3, 3, 100) X, Y = np.meshgrid(x, y) Z = np.sin(X**2 + Y**2) # Contour plot with custom line styles levels = [-0.9, -0.6, -0.3, 0, 0.3, 0.6, 0.9] plt.contour(X, Y, Z, levels=levels, linestyles=[”-”, ”–”, ”-.”, ”:”, ”-”, ”–”]) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Manual Contour Plot with Customized Line Styles”) plt.show() Output On executing the above code we will get the following output − Print Page Previous

Matplotlib – Violin Plot

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 ”;

Matplotlib – Useful Resources

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 ”;