Matplotlib – Choosing Colormaps ”; Previous Next Colormap also known as a color table or a palette, is a range of colors that represents a continuous range of values. Allowing you to represent information effectively through color variations. See the below image referencing a few built-in colormaps in matplotlib − Matplotlib offers a variety of built-in (available in matplotlib.colormaps module) and third-party colormaps for various applications. Choosing Colormaps in Matplotlib Choosing an appropriate colormap involves finding a suitable representation in 3D colorspace for your dataset. The factors for selecting an appropriate colormap for any given data set include − Nature of Data − Whether representing form or metric data Knowledge of the Dataset − Understanding the dataset”s characteristics. Intuitive Color Scheme − Considering if there”s an intuitive color scheme for the parameter being plotted. Field Standards − Considering if there is a standard in the field the audience may be expecting. A perceptually uniform colormap is recommended for most of the applications, ensuring equal steps in data are perceived as equal steps in the color space. This improves human brain interpretation, particularly when changes in lightness are more perceptible than changes in hue. Categories of Colormaps Colormaps are categorized based on their function − Sequential − Incremental changes in lightness and saturation, often using a single hue. Suitable for representing ordered information. Diverging − Changes in lightness and saturation of two colors, meeting at an unsaturated color. Ideal for data with a critical middle value, like topography or data deviating around zero. Cyclic − Changes in the lightness of two colors, meeting at the middle and beginning/end at an unsaturated color. Suitable for values that wrap around at endpoints, such as phase angle or time of day. Qualitative − Miscellaneous colors with no specific order. Used for representing information without ordering or relationships. Sequential Colormaps Sequential colormaps show a monotonically increasing in lightness values as they increase through the colormap. This characteristic ensures a smooth transition in the perception of color changes, making them suitable for representing ordered information. However, it”s essential to note that the perceptual range may vary among colormaps, depending on the range of values they span. Let”s explore Sequential colormaps by visualizing their gradients and understanding how their lightness values evolve. Example The following example provides a visual representation of the gradients for different Sequential colormaps available in Matplotlib. import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl # List of Sequential colormaps to visualize cmap_list = [”Greys”, ”Purples”, ”Blues”, ”Greens”, ”Oranges”, ”Reds”, ”YlOrBr”, ”YlOrRd”, ”OrRd”, ”PuRd”, ”RdPu”, ”BuPu”, ”GnBu”, ”PuBu”, ”YlGnBu”, ”PuBuGn”, ”BuGn”, ”YlGn”] # Plot the color gradients gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) # Create figure and adjust figure height to the number of colormaps nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + (nrows – 1) * 0.1) * 0.22 fig, axs = plt.subplots(nrows=nrows + 1, figsize=(7, figh)) fig.subplots_adjust(top=1 – 0.35 / figh, bottom=0.15 / figh, left=0.2, right=0.99) axs[0].set_title(”Sequential colormaps”, fontsize=14) for ax, name in zip(axs, cmap_list): ax.imshow(gradient, aspect=”auto”, cmap=mpl.colormaps[name]) ax.text(-0.1, 0.5, name, va=”center”, ha=”right”, fontsize=10, transform=ax.transAxes) # Turn off all ticks & spines, not just the ones with colormaps. for ax in axs: ax.set_axis_off() # Show the plot plt.show() Output On executing the above code we will get the following output − Diverging Colormaps Diverging colormaps are characterized by monotonically increasing and then decreasing lightness values, with the maximum lightness close to a neutral midpoint. Example The following example provides a visual representation of the gradients for different Diverging colormaps available in Matplotlib. import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl # List of Diverging colormaps to visualize cmap_list = [”PiYG”, ”PRGn”, ”BrBG”, ”PuOr”, ”RdGy”, ”RdBu”, ”RdYlBu”, ”RdYlGn”, ”Spectral”, ”coolwarm”, ”bwr”, ”seismic”] # Plot the color gradients gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) # Create figure and adjust figure height to the number of colormaps nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + (nrows – 1) * 0.1) * 0.22 fig, axs = plt.subplots(nrows=nrows + 1, figsize=(7, figh)) fig.subplots_adjust(top=1 – 0.35 / figh, bottom=0.15 / figh, left=0.2, right=0.99) axs[0].set_title(”Diverging colormaps”, fontsize=14) for ax, name in zip(axs, cmap_list): ax.imshow(gradient, aspect=”auto”, cmap=mpl.colormaps[name]) ax.text(-0.1, 0.5, name, va=”center”, ha=”left”, fontsize=10, transform=ax.transAxes) # Turn off all ticks & spines, not just the ones with colormaps. for ax in axs: ax.set_axis_off() # Show the plot plt.show() Output On executing the above code we will get the following output − Cyclic Colormaps Cyclic colormaps present a unique design where the colormap starts and ends on the same color, meeting at a symmetric center point. The progression of lightness values should change monotonically from the start to the middle and inversely from the middle to the end. Example In the following example, you can explore and visualize various Cyclic colormaps available in Matplotlib. import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl # List of Cyclic colormaps to visualize cmap_list = [”twilight”, ”twilight_shifted”, ”hsv”] # Plot the color gradients gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) # Create figure and adjust figure height to the number of colormaps nrows = len(cmap_list) figh = 0.35 + 0.15 + (nrows + (nrows – 1) * 0.1) * 0.22 fig, axs = plt.subplots(nrows=nrows + 1, figsize=(7, figh)) fig.subplots_adjust(top=1 – 0.35 / figh, bottom=0.15 / figh, left=0.2, right=0.99) axs[0].set_title(”Cyclic colormaps”, fontsize=14) for ax, name in zip(axs, cmap_list): ax.imshow(gradient, aspect=”auto”, cmap=mpl.colormaps[name]) ax.text(-0.1, 0.5, name, va=”center”, ha=”left”, fontsize=10, transform=ax.transAxes) # Turn off all ticks & spines, not just the ones with colormaps. for ax in axs: ax.set_axis_off() # Show the
Category: matplotlib
Matplotlib – Styles
Matplotlib – Styles ”; Previous Next What is Style in Matplotlib? In Matplotlib library styles are configurations that allow us to change the visual appearance of our plots easily. They act as predefined sets of aesthetic choices by altering aspects such as colors, line styles, fonts, gridlines and more. These styles help in quickly customizing the look and feel of our plots without manually adjusting individual elements each time. We can experiment with different styles to find the one that best suits our data or visual preferences. Styles provide a quick and efficient way to enhance the visual presentation of our plots in Matplotlib library. Built-in Styles Matplotlib comes with a variety of built-in styles that offer different color schemes, line styles, font sizes and other visual properties. Examples include ggplot, seaborn, classic, dark_background and more. Changing Styles Use plt.style.use(”style_name”) to apply a specific style to our plots. Key Aspects of Matplotlib Styles Predefined Styles − Matplotlib library comes with various built-in styles that offer different aesthetics for our plots. Ease of Use − By applying a style we can instantly change the overall appearance of our plot to match different themes or visual preferences. Consistency − Styles ensure consistency across multiple plots or figures within the same style setting. Using Styles There are several steps involved in using the available styles in matlplotlib library. Let’s see them one by one. Setting a Style For setting the required style we have to use plt.style.use(”style_name”) to set a specific style before creating our plots. For example if we want to set the ggplot style we have to use the below code. import matplotlib.pyplot as plt plt.style.use(”ggplot”) # Setting the ”ggplot” style Available Styles We can view the list of available styles using plt.style.available. Example import matplotlib.pyplot as plt print(plt.style.available) # Prints available styles Output [”Solarize_Light2”, ”_classic_test_patch”, ”_mpl-gallery”, ”_mpl-gallery-nogrid”, ”bmh”, ”classic”, ”dark_background”, ”fast”, ”fivethirtyeight”, ”ggplot”, ”grayscale”, ”seaborn”, ”seaborn-bright”, ”seaborn-colorblind”, ”seaborn-dark”, ”seaborn-dark-palette”, ”seaborn-darkgrid”, ”seaborn-deep”, ”seaborn-muted”, ”seaborn-notebook”, ”seaborn-paper”, ”seaborn-pastel”, ”seaborn-poster”, ”seaborn-talk”, ”seaborn-ticks”, ”seaborn-white”, ”seaborn-whitegrid”, ”tableau-colorblind10”] Applying Custom Styles We can create custom style files with specific configurations and then use plt.style.use(”path_to_custom_style_file”) to apply them. Applying the seaborn-darkgrid style In this example the style ”seaborn-darkgrid” is applying to the plot altering its appearance. Example import matplotlib.pyplot as plt # Using a specific style plt.style.use(”seaborn-darkgrid”) # Creating a sample plot plt.plot([1, 2, 3, 4], [10, 15, 25, 30]) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Sample Plot”) plt.show() Output Applying ggplot style In this example we are using the ggplot style for our plot. Example import matplotlib.pyplot as plt # Using a specific style plt.style.use(”seaborn-white”) # Creating a sample plot plt.plot([1, 2, 3, 4], [10, 15, 25, 30]) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Sample Plot”) plt.show() Output Print Page Previous Next Advertisements ”;
Matplotlib – Enabling LaTex Rendering in Annotations ”; Previous Next What is LaTex Rendering? LaTeX rendering refers to the process of converting LaTeX markup language which contains typesetting instructions and commands, into formatted output. This output is typically high-quality documents, mathematical formulas, scientific papers or technical reports with precise and consistent typography. LaTeX rendering is widely used in academia, scientific research, technical documentation and publishing due to its robust typesetting capabilities and its ability to produce professional-looking documents. Key Aspects of LaTeX Rendering Typesetting − LaTeX is renowned for its superior typesetting capabilities ensuring professional-grade document formatting for academic and technical content. Mathematical Formulas − LaTeX is extensively used for its exceptional support in typesetting complex mathematical equations by making it a preferred choice for academic and scientific publications. Markup Language − LaTeX uses a markup language in which, where users write documents with plain text and include commands to specify formatting, structure and content. Compilation − The LaTeX source code needs to be compiled using a LaTeX compiler such as pdflatex, xelatex, lualatex. During compilation the compiler interprets the LaTeX commands and generates the final output in various formats like PDF, DVI or PostScript. Customization − LaTeX allows users to create custom styles, templates and packages by enabling precise control over document formatting and layout. Benefits of LaTeX Rendering Quality and Consistency − LaTeX ensures high-quality and consistent document formatting across various platforms and devices. Mathematical Typesetting − It excels in handling complex mathematical notation and making it indispensable for scientific and mathematical content. Cross-Platform Compatibility − LaTeX documents can be easily compiled and viewed on different operating systems. Version Control − Plain text-based source files facilitate version control systems by making collaboration and document history management easier. Enabling Latex Rendering To enable LaTeX rendering for creating documents, equations or annotations we typically need the following. LaTeX Installation Install a LaTeX distribution like TeX Live, MiKTeX or MacTeX which includes the necessary LaTeX compiler and packages. Text Editor Choose a text editor or an integrated development environment (IDE) that supports LaTeX such as TeXstudio, TeXworks, Overleaf or editors like Sublime Text, VS Code or Atom with LaTeX plugins/extensions. Write LaTeX Code Create a .tex file and write LaTeX code using the appropriate commands and syntax to structure our document which include equations or format text. Compilation Use the LaTeX compiler to compile the .tex file into the desired output format such as PDF, DVI, PS. Run the appropriate command in the terminal or use the integrated features of our chosen editor/IDE. For example in a terminal we might run the following code. Example pdflatex your_file.tex Or within an editor/IDE there”s often a Build or Compile button to initiate the compilation process. LaTeX Rendering in Matplotlib for Annotations For Matplotlib annotations using LaTeX for text formatting within plots we have to ensure the below. Matplotlib Support − Matplotlib supports LaTeX for annotations by using LaTeX syntax within plt.annotate() or similar functions. LaTeX Installation − Ensure we have a working LaTeX installation on our system that Matplotlib can access for rendering LaTeX text within annotations. Correct Syntax − Use the correct LaTeX syntax r”$…$” within Matplotlib functions for annotations to render the desired LaTeX-formatted text. By following the above mentioned steps we can enable LaTeX rendering for various purposes such as document creation, mathematical notation or annotations in visualization libraries like Matplotlib. Enabling LaTex Rendering In this example we are going to use the LaTex rendering in the annotations of the plot. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4] y = [2, 5, 7, 10] plt.plot(x, y, ”o-”, label=”Data”) # Annotating a point with LaTeX-rendered text plt.annotate(r”$sum_{i=1}^{4} y_i$”, # LaTeX expression within the annotation xy=(x[2], y[2]), # Coordinates of the annotation point xytext=(2.5, 6), # Text position arrowprops=dict(facecolor=”black”, arrowstyle=”->”), fontsize=12, color=”green”) # Labeling axes and title plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Plot with LaTeX rendering in Annotation”) plt.legend() plt.show() Output On executing the above code you will get the following output − Example Here this is another example of using the LaTex rendering in annotations of a plot. import matplotlib.pyplot as plt # Generating some data points x = [1, 2, 3, 4] y = [2, 5, 7, 10] plt.plot(x, y, ”o-”, label=”Data”) # Annotating a point with LaTeX rendering plt.annotate(r”textbf{Max Value}”, xy=(x[y.index(max(y))], max(y)), xytext=(2.5, 8), arrowprops=dict(facecolor=”black”, shrink=0.05), fontsize=12, color=”white”, bbox=dict(boxstyle=”round,pad=0.3”, edgecolor=”red”, facecolor=”green”)) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Example Plot with LaTeX Annotation”) plt.legend() plt.show() Output On executing the above code you will get the following output − Change the axis tick font in a Matplotlib plot when rendering using LaTex Here this is the example to change the axis tick font in matplotlib when rendering using LaTeX Example import numpy as np import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True x = np.array([1, 2, 3, 4]) y = np.exp(x) ax1 = plt.subplot() ax1.set_xticks(x) ax1.set_yticks(y) ax1.plot(x, y, c=”red”) ax1.set_xticklabels([r”$bf{one}$”, r”$bf{two}$”, r”$bf{three}$”, r”$bf{four}$”], rotation=45) ax1.set_yticklabels([r”$bf{:.2f}$”.format(y[0]), r”$bf{:.2f}$”.format(y[1]), r”$bf{:.2f}$”.format(y[2]), r”$bf{:.2f}$”.format(y[3])], rotation=45) plt.tight_layout() plt.show() Output On executing the above code you will get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Colors
Matplotlib – Colors ”; Previous Next Matplotlib provides several options for managing colors in plots, allowing users to enhance the visual appeal and convey information effectively. Colors can be set for different elements in a plot, such as lines, markers, and fill areas. For instance, when plotting data, the color parameter can be used to specify the line color. Similarly, scatter plots allow setting colors for individual points. The image below illustrates the colors for the different elements in a plot − Color Representation Formats in Matplotlib Matplotlib supports various formats for representing colors, which include − RGB or RGBA Tuple Hex RGB or RGBA String Gray Level String “Cn” Color Spec Named colors Below are the brief discussions about each format with an appropriate example. The RGB or RGBA Tuple format You can use the tuple of float values in the range between [0, 1] to represent Red, Green, Blue, and Alpha (transparency) values. like: (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3). Example The following example demonstrates how to specify the face color of a plot using the RGB or RGBA tuple. import matplotlib.pyplot as plt import numpy as np # sample data t = np.linspace(0.0, 2.0, 201) s = np.sin(2 * np.pi * t) # RGB tuple for specifying facecolor fig, ax = plt.subplots(figsize=(7,4), facecolor=(.18, .31, .31)) # Plotting the data plt.plot(t, s) # Show the plot plt.show() print(”successfully used the RGB tuple for specifying colors..”) Output On executing the above code we will get the following output − successfully used the RGB tuple for specifying colors.. The Hex RGB or RGBA String format A string representing the case-insensitive hex RGB or RGBA, like: ”#0F0F0F” or ”#0F0F0F0F” can be used to specify a color in matplotlib. Example This example uses the hex string to specify the axis face color. import matplotlib.pyplot as plt import numpy as np # Example data t = np.linspace(0.0, 2.0, 201) s = np.sin(2 * np.pi * t) # Hex string for specifying axis facecolor fig, ax = plt.subplots(figsize=(7,4)) ax.set_facecolor(”#eafff5”) # Plotting the data plt.plot(t, s) # Show the plot plt.show() print(”successfully used the Hex string for specifying colors..”) Output On executing the above code we will get the following output − successfully used the Hex string for specifying colors.. Also, a shorthand hex RGB or RGBA string(case-insensitive) can be used to specify colors in matplotlib. Which are equivalent to the hex shorthand of duplicated characters. like: ”#abc” (equivalent to ”#aabbcc”) or ”#abcd” (equivalent to ”#aabbccdd”). The Gray Level String format We can use a string representation of a float value in the range of [0, 1] inclusive for the gray level. For example, ”0” represents black, ”1” represents white, and ”0.8” represents light gray. Example Here is an example of using the Gray level string for specifying the title color. import matplotlib.pyplot as plt import numpy as np # Example data t = np.linspace(0.0, 2.0, 201) s = np.sin(2 * np.pi * t) # create a plot fig, ax = plt.subplots(figsize=(7,4)) # Plotting the data plt.plot(t, s) # using the Gray level string for specifying title color ax.set_title(”Voltage vs. time chart”, color=”0.7”) # Show the plot plt.show() print(”successfully used the Gray level string for specifying colors..”) Output On executing the above code we will get the following output − successfully used the Gray level string for specifying colors.. The “Cn” Color notation A “Cn” color Spec, i.e., ”C” followed by a number, which is an index into the default property cycle (rcParams[“axes.prop_cycle”]) can be used to specify the colors in matplotlib. Example In this example, a plot is drawn using the Cn notation (color=”C1”), which corresponds to the 2nd color in the default property cycle. import matplotlib.pyplot as plt import numpy as np # Example data t = np.linspace(0.0, 2.0, 201) s = np.sin(2 * np.pi * t) # create a plot fig, ax = plt.subplots(figsize=(7,4)) # Cn notation for plot ax.plot(t, .7*s, color=”C1”, linestyle=”–”) # Show the plot plt.show() print(”successfully used the Cn notation for specifying colors..”) Output On executing the above code we will get the following output − successfully used the Cn notation for specifying colors.. The Single Letter String format In Matplotlib, single-letter strings are used as shorthand notations to represent a set of basic colors. These shorthand notations are part of the base colors available as a dictionary in matplotlib.colors.BASE_COLORS container. And each letter corresponds to a specific color. The single-letter shorthand notations include: ”b”: Blue, ”g”: Green, ”r”: Red, ”c”: Cyan, ”m”: Magenta, ”y”: Yellow, ”k”: Black, and ”w”: White. Example In this example, each base color is plotted as a bar with its corresponding single-letter shorthand notation. import matplotlib.pyplot as plt import matplotlib.colors as mcolors import numpy as np # Get the base colors and their names base_colors = mcolors.BASE_COLORS color_names = list(base_colors.keys()) # Create a figure and axis fig, ax = plt.subplots(figsize=(7, 4)) # Plot each color as a bar for i, color_name in enumerate(color_names): ax.bar(i, 1, color=base_colors[color_name], label=color_name) # Set the x-axis ticks and labels ax.set_xticks(np.arange(len(color_names))) ax.set_xticklabels(color_names) # Set labels and title ax.set_title(”Base Colors”) # Add legend ax.legend() # Show the plot plt.show() print(”Successfully visualized all the available base colors..”) Output On executing the above code we will get the following output − Successfully visualized all the available base colors.. Other formats Also we can use the Case-insensitive color name from the xkcd color survey with ”xkcd:” prefix, X11/CSS4 (“html”) Color
Matplotlib – Introduction
Matplotlib – Introduction ”; Previous Next Matplotlib is a powerful and widely-used plotting library in Python which enables us to create a variety of static, interactive and publication-quality plots and visualizations. It”s extensively used for data visualization tasks and offers a wide range of functionalities to create plots like line plots, scatter plots, bar charts, histograms, 3D plots and much more. Matplotlib library provides flexibility and customization options to tailor our plots according to specific needs. It is a cross-platform library for making 2D plots from data in arrays. Matplotlib is written in Python and makes use of NumPy, the numerical mathematics extension of Python. 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. Matplotlib has a procedural interface named the Pylab which is designed to resemble MATLAB a proprietary programming language developed by MathWorks. Matplotlib along with NumPy can be considered as the open source equivalent of MATLAB. Matplotlib was originally written by John D. Hunter in 2003. The current stable version is 2.2.0 released in January 2018. The most common way to use Matplotlib is through its pyplot module. The following are the in-depth overview of Matplotlib”s key components and functionalities − Components of Matplotlib Figure A figure is the entire window or page that displays our plot or collection of plots. It acts as a container that holds all elements of a graphical representation which includes axes, labels, legends and other components. Example This is the basic plot which represents the figure. import matplotlib.pyplot as plt # Create a new figure fig = plt.figure() # Add a plot or subplot to the figure plt.plot([1, 2, 3], [4, 5, 6]) plt.show() Output Axes/Subplot A specific region of the figure in which the data is plotted. Figures can contain multiple axes or subplots. The following is the example of the axes/subplot. Example import matplotlib.pyplot as plt # Creating a 2×2 grid of subplots fig, axes = plt.subplots(nrows=2, ncols=2) # Accessing individual axes (subplots) axes[0, 0].plot([1, 2, 3], [4, 5, 6]) # Plot in the first subplot (top-left) axes[0, 1].scatter([1, 2, 3], [4, 5, 6]) # Second subplot (top-right) axes[1, 0].bar([1, 2, 3], [4, 5, 6]) # Third subplot (bottom-left) axes[1, 1].hist([1, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5]) # Fourth subplot (bottom-right) plt.show() Output Axis An axis refers to the X-axis or Y-axis in a plot or it can also denote an individual axis within a set of subplots. Understanding axes is essential for controlling and customizing the appearance and behavior of plots in Matplotlib. The following is the plot which contains the axis. Example import matplotlib.pyplot as plt # Creating a plot plt.plot([1, 2, 3, 4], [10, 20, 25, 30]) # Customizing axis limits and labels plt.xlim(0, 5) plt.ylim(0, 35) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.show() Output Artist Artists refer to the various components or entities that make up a plot such as figures, axes, lines, text, patches, shapes (rectangles or circles) and more. They are the building blocks used to create visualizations and are organized in a hierarchy. The below is the plot which resembles all the components of an artist. Example import matplotlib.pyplot as plt # Create a figure and an axis (subplot) fig, ax = plt.subplots() # Plot a line (artist) line = ax.plot([1, 2, 3], [4, 5, 6], label=”Line”)[0] # Modify line properties line.set_color(”red”) line.set_linewidth(2.5) # Add labels and title (text artists) ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) ax.set_title(”Artist Plot”) plt.legend() plt.show() Output Key Features Simple Plotting − Matplotlib allows us to create basic plots easily with just a few lines of code. Customization − We can extensively customize plots by adjusting colors, line styles, markers, labels, titles and more. Multiple Plot Types − It supports a wide variety of plot types such as line plots, scatter plots, bar charts, histograms, pie charts, 3D plots, etc. Publication Quality − Matplotlib produces high-quality plots suitable for publications and presentations with customizable DPI settings. Support for LaTeX Typesetting − We can use LaTeX for formatting text and mathematical expressions in plots. Types of Plots Matplotlib supports various types of plots which are as mentioned below. Each plot type has its own function in the library. Name of the plot Definition Image Line plot A line plot is a type of graph that displays data points connected by straight line segments. The plt.plot() function of the matplotlib library is used to create the line plot. Scatter plot A scatter plot is a type of graph that represents individual data points by displaying them as markers on a two-dimensional plane. The plt.scatter() function is used to plot the scatter plot. Line plot A line plot is a type of graph that displays data points connected by straight line segments. The plt.plot() function of the matplotlib library is used to create the line plot. Bar plot A bar plot or bar chart is a visual representation of categorical data using rectangular bars. The plt.bar() function is used to plot the bar plot. Pie plot A pie plot is also known as a pie chart. It is a circular statistical graphic used to illustrate numerical proportions. It divides a circle into sectors or slices to represent the relative sizes or percentages of categories within a dataset. The plt.pie() function is used to plot the pie chart. The
Matplotlib – Legends
Matplotlib – Legends ”; Previous Next In general, a legend in a graph provides a visual representation of the data depicted along the Y-axis, often referred to as the graph series. It is a box containing a symbol and a label for each series in the graph. A series could be a line in a line chart, a bar in a bar chart, and so on. The legend is helpful when you have multiple data series on the same plot, and you want to distinguish between them. In the following image, we can observe the legend in a plot (highlighted with a red color rectangle) − Adding legend to a matplotlib plot To add a legend to a Matplotlib plot, you typically use the matplotlib.pyplot.legend() function. This function is used to add a legend to the Axes, providing a visual guide for the elements in the plot. Syntax Following is the syntax of the function matplotlib.pyplot.legend(*args, **kwargs) The function can be called in different ways, depending on how you want to customize the legend. Matplotlib automatically determines the elements to be added to the legend while call legend() without passing any extra arguments,. The labels for these elements are taken from the artists in the plot. You can specify these labels either at the time of creating the artist or by using the set_label() method. Example 1 In this example, the legend takes the data from the label argument is used when creating the plot. import matplotlib.pyplot as plt # Example data x = [1, 2, 3] y = [2, 4, 6] # Plotting the data with labels line, = plt.plot(x, y, label=”Legend describing a single line”) # Adding a legend plt.legend() # Show the plot plt.show() print(”Successfully Placed a legend on the Axes…”) Output Successfully Placed a legend on the Axes… Example 2 Here is the alternative way of using the set_label() method on the artist. import matplotlib.pyplot as plt # Example data x = [1, 2, 3] y = [2, 4, 6] # Plotting the data with labels line, = plt.plot(x, y) line.set_label(”Place a legend via method”) # Adding a legend plt.legend() # Show the plot plt.show() print(”Successfully Placed a legend on the Axes…”) Output Successfully Placed a legend on the Axes… Manually adding the legend You can pass an iterable of legend artists followed by an iterable of legend labels to explicitly control which artists have a legend entry. Example 1 Here is an example of calling the legend() function by listing artists and labels. import matplotlib.pyplot as plt # Example data x = [1, 2, 3] y1 = [2, 4, 6] y2 = [1, 3, 5] y3 = [3, 6, 9] # Plotting the data line1, = plt.plot(x, y1) line2, = plt.plot(x, y2) line3, = plt.plot(x, y3) # calling legend with explicitly listed artists and labels plt.legend([line1, line2, line3], [”Label 1”, ”Label 2”, ”Label 3”]) # Show the plot plt.show() print(”Successfully Placed a legend on the Axes…”) Output Successfully Placed a legend on the Axes… Example 2 Here is an example of calling the legend() function only by listing the artists. This approach is similar to the previous one but in this case, the labels are taken from the artists” label properties. import matplotlib.pyplot as plt # Example data x = [1, 2, 3] y1 = [2, 4, 6] y2 = [1, 3, 5] # Plotting the data with labels line1, = plt.plot(x, y1, label=”Label 1”) line2, = plt.plot(x, y2, label=”Label 2”) # Adding a legend with explicitly listed artists plt.legend(handles=[line1, line2]) # Show the plot plt.show() print(”Successfully Placed a legend on the Axes…”) Output Successfully Placed a legend on the Axes… Example 3 In this example, we first plot two sets of data, and then we add a legend by calling the legend() function with a list of strings representing the legend items. import matplotlib.pyplot as plt # Example data x = [1, 2, 3, 4, 5, 6] y1 = [1, 4, 2, 6, 8, 5] y2 = [1, 5, 3, 7, 9, 6] # Plotting the data plt.plot(x, y1) plt.plot(x, y2) # Adding a legend for existing plot elements plt.legend([”First line”, ”Second line”], loc=”center”) # Show the plot plt.show() print(”Successfully Placed a legend on the Axes…”) Output Successfully Placed a legend on the Axes… Adding legend in subplots To add the legends in each subplot, we can use the legend() function on each axes object of the figure. Example 1 Here is an example that adds the legend to the each subplot of a matplotlib figure. This approach uses the legend() function on the axes object. import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7, 3.50] plt.rcParams[“figure.autolayout”] = True # Sample data x = np.linspace(-2, 2, 100) y1 = np.sin(x) y2 = np.cos(x) y3 = np.tan(x) # Create the figure with subplots f, axes = plt.subplots(3) # plot the data on each subplot and add lagend axes[0].plot(x, y1, c=”r”, label=”sine”) axes[0].legend(loc=”upper left”) axes[1].plot(x, y2, c=”g”, label=”cosine”) axes[1].legend(loc=”upper left”) axes[2].plot(x, y3, c=”b”, label=”tan”) axes[2].legend(loc=”upper left”) # Display the figure plt.show() Output On executing the above code we will get the following output − Adding multiple legends in one axes To draw multiple legends on the same axes in Matplotlib, we can use the axes.add_artist() method along with the legend() function. Example 2 The following example demonstrates how to add multiple legends in one axes of the matplotlib figure. from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7,
Matplotlib – Colormap Normalization ”; Previous Next The term normalization refers to the rescaling of real values to a common range, such as between 0 and 1. It is commonly used as per−processing technique in data processing and analysis. Colormap Normalization in Matplotlib In this context, Normalization is the process of mapping data values to colors. The Matplotlib library provides various normalization techniques, including − Logarithmic Centered Symmetric logarithmic Power-law Discrete bounds Two-slope Custom normalization Linear Normalization The default behavior in Matplotlib is to linearly map colors based on data values within a specified range. This range is typically defined by the minimum (vmin) and maximum (vmax) values of the matplotlib.colors.Normalize() instance arguments. This mapping occurs in two steps, first normalizing the input data to the [0, 1] range and then mapping ont the indices in the colormap. Example This example demonstrates Matplotlib”s linear normalization process using the Normalize() class from the matplotlib.colors module. import matplotlib as mpl from matplotlib.colors import Normalize # Creates a Normalize object with a specified range norm = Normalize(vmin=-1, vmax=1) # Normalizing a value normalized_value = norm(0) # Display the normalized value print(”Normalized Value”, normalized_value) Output On executing the above code we will get the following output − Normalized Value: 0.5 While linear normalization is the default and often suitable, there are scenarios where non-linear mappings can be more informative or visually appealing. Logarithmic Normalization It is a common transformation that takes the logarithm (base-10) of the data. This is useful when displaying changes across disparate scales. The colors.LogNorm() class is used for this normalization. Example In this example, two subplots are created to demonstrate the difference between logarithmic and linear normalization transformations. import matplotlib.pyplot as plt import numpy as np from matplotlib import colors # Sample Data X, Y = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128)) Z = (1 – X/2 + X**5 + Y**3) * np.exp(-X**2 – Y**2) # Create subplots fig, ax = plt.subplots(1, 2, figsize=(7,4), layout=”constrained”) # Logarithmic Normalization pc = ax[0].imshow(Z**2 * 100, cmap=”plasma”, norm=colors.LogNorm(vmin=0.01, vmax=100)) fig.colorbar(pc, ax=ax[0], extend=”both”) ax[0].set_title(”Logarithmic Normalization”) # Linear Normalization pc = ax[1].imshow(Z**2 * 100, cmap=”plasma”, norm=colors.Normalize(vmin=0.01, vmax=100)) fig.colorbar(pc, ax=ax[1], extend=”both”) ax[1].set_title(”Linear Normalization”) plt.show() Output On executing the above code we will get the following output − Centered Normalization When data is symmetrical around a center (e.g., positive and negative anomalies around 0), the colors.CenteredNorm() class can be used. It automatically maps the center to 0.5, and the point with the largest deviation from the center to 1.0 or 0.0, depending on its value. Example This example compares the effects of default linear normalization and centered normalization (CenteredNorm()) on the dataset using a coolwarm colormap. import matplotlib.pyplot as plt import numpy as np from matplotlib import colors, cm X, Y = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128)) Z = (1 – X/2 + X**5 + Y**3) * np.exp(-X**2 – Y**2) # select a divergent colormap cmap = cm.coolwarm # Create subplots fig, ax = plt.subplots(1, 2, figsize=(7,4), layout=”constrained”) # Default Linear Normalization pc = ax[0].pcolormesh(Z, cmap=cmap) fig.colorbar(pc, ax=ax[0]) ax[0].set_title(”Normalize”) # Centered Normalization pc = ax[1].pcolormesh(Z, norm=colors.CenteredNorm(), cmap=cmap) fig.colorbar(pc, ax=ax[1]) ax[1].set_title(”CenteredNorm()”) plt.show() Output On executing the above code we will get the following output − Symmetric Logarithmic Normalization If data may contain both positive and negative values, and logarithmic scaling is desired for both. The colors.SymLogNorm() Class in Matplotlib is designed for such cases. This normalization maps negative numbers logarithmically to smaller values, and positive numbers to larger values. Example Here is an example that uses the colors.SymLogNorm() Class to transform the data. import matplotlib.pyplot as plt import numpy as np from matplotlib import colors, cm X, Y = np.mgrid[-3:3:complex(0, 128), -2:2:complex(0, 128)] Z = (1 – X/2 + X**5 + Y**3) * np.exp(-X**2 – Y**2) # Create subplots fig, ax = plt.subplots(1, 2, figsize=(7, 4), layout=”constrained”) # Symmetric Logarithmic Normalization pcm = ax[0].pcolormesh(X, Y, Z, norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,vmin=-1.0, vmax=1.0, base=10), cmap=”plasma”, shading=”auto”) fig.colorbar(pcm, ax=ax[0]) ax[0].set_title(”SymLogNorm()”) # Default Linear Normalization pcm = ax[1].pcolormesh(X, Y, Z, cmap=”plasma”, vmin=-np.max(Z), shading=”auto”) fig.colorbar(pcm, ax=ax[1]) ax[1].set_title(”Normalize”) plt.show() Output On executing the above code we will get the following output − Power-law Normalization This normalization is useful to remap colors onto a power-law relationship using the colors.PowerNorm() class. Example Here is an example that compares the power-law (colors.PowerNorm()) and linear normalizations. import matplotlib.pyplot as plt import numpy as np from matplotlib import colors, cm X, Y = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128)) Z = (1 + np.sin(Y * 10.)) * X**2 # Create subplots fig, ax = plt.subplots(1, 2, figsize=(7, 4), layout=”constrained”) # Power-law Normalization pcm = ax[0].pcolormesh(X, Y, Z, norm=colors.PowerNorm(gamma=0.5), cmap=”PuBu_r”, shading=”auto”) fig.colorbar(pcm, ax=ax[0]) ax[0].set_title(”PowerNorm()”) # Default Linear Normalization pcm = ax[1].pcolormesh(X, Y, Z, cmap=”PuBu_r”, shading=”auto”) fig.colorbar(pcm, ax=ax[1]) ax[1].set_title(”Normalize”) plt.show() Output On executing the above code we will get the following output − Discrete Bounds Normalization Another normalization provided by Matplotlib is colors.BoundaryNorm. This is particularly useful when data needs to be mapped between specified boundaries with linearly distributed colors. Example This example demonstrates the use of the Discrete Bounds normalization using the BoundaryNorm() class to create different visual effects when displaying a colormesh plot. import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as colors X, Y = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128)) Z = (1 + np.sin(Y * 10.)) * X**2 fig, ax = plt.subplots(2, 2, figsize=(7, 6), layout=”constrained”) ax = ax.flatten() # Default norm: pcm = ax[0].pcolormesh(X, Y, Z, cmap=”RdBu_r”) fig.colorbar(pcm, ax=ax[0], orientation=”vertical”) ax[0].set_title(”Default norm”) #
Matplotlib – Figures
Matplotlib – Figures ”; Previous Next In Matplotlib library a figure is the top-level container that holds all elements of a plot or visualization. It can be thought of as the window or canvas where plots are created. A single figure can contain multiple subplots i.e. axes, titles, labels, legends and other elements. The figure() function in Matplotlib is used to create a new figure. Syntax The below is the syntax and parameters of the figure() method. plt.figure(figsize=(width, height), dpi=resolution) Where, figsize=(width, height) − Specifies the width and height of the figure in inches. This parameter is optional. dpi=resolution − Sets the resolution or dots per inch for the figure. Optional and by default is 100. Creating a Figure To create the Figure by using the figure() method we have to pass the figure size and resolution values as the input parameters. Example import matplotlib.pyplot as plt # Create a figure plt.figure(figsize=(3,3), dpi=100) plt.show() Output Figure size 300×300 with 0 Axes Adding Plots to a Figure After creating a figure we can add plots or subplots (axes) within that figure using various plot() or subplot() functions in Matplotlib. Example import matplotlib.pyplot as plt # Create a figure plt.figure(figsize=(3, 3), dpi=100) x = [12,4,56,77] y = [23,5,7,21] plt.plot(x,y) plt.show() Output Displaying and Customizing Figures To display and customize the figures we have the functions plt.show(),plt.title(), plt.xlabel(), plt.ylabel(), plt.legend(). plt.show() This function displays the figure with all the added plots and elements. Customization We can perform customizations such as adding titles, labels, legends and other elements to the figure using functions like plt.title(), plt.xlabel(), plt.ylabel(), plt.legend() etc. Example In this example we are using the figure() method of the pyplot module by passing the figsize as (8,6) and dpi as 100 to create a figure with a line plot and includes customization options such as a title, labels and a legend. Figures can contain multiple plots or subplots allowing for complex visualizations within a single window. import matplotlib.pyplot as plt # Data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Create a figure plt.figure(figsize=(8, 6), dpi=100) # Add a line plot to the figure plt.plot(x, y, label=”Line Plot”) # Customize the plot plt.title(”Figure with Line Plot”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.legend() # Display the figure plt.show() Output Example Here this is another example of using the figure() method of the pyplot module to create the subplots. import matplotlib.pyplot as plt # Create a figure plt.figure(figsize=(8, 6)) # Add plots or subplots within the figure plt.plot([1, 2, 3], [2, 4, 6], label=”Line 1”) plt.scatter([1, 2, 3], [3, 5, 7], label=”Points”) # Customize the figure plt.title(”Example Figure”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.legend() # Display the figure plt.show() Output Print Page Previous Next Advertisements ”;
Matplotlib – Vs Seaborn
Matplotlib VS Seaborn ”; Previous Next Matplotlib and Seaborn are both powerful Python libraries used for data visualization but they have different strengths that are suited for different purposes. What is Matplotlib? Matplotlib is a comprehensive and widely used Python library for creating static, interactive and publication-quality visualizations. It provides a versatile toolkit for generating various types of plots and charts which makes it an essential tool for data scientists, researchers, engineers and analysts. The following are the features of the matplotlib library. Core Library Matplotlib is the foundational library for plotting in Python. It provides low-level control over visualizations by allowing users to create a wide variety of plots from basic to highly customize. Customization It offers extensive customization options by allowing users to control every aspect of a plot. This level of control can sometimes result in more code for creating complex plots. Basic Plotting While it”s highly flexible for creating certain complex plots might require more effort and code compared to specialized libraries like Seaborn. Simple plot by matplotlib The following is the simple line plot created by using the matplotlib lbrary pyplot module. Example import matplotlib.pyplot as plt # Creating a plot plt.plot([1, 2, 3, 4], [10, 20, 25, 30]) # Customizing axis limits and labels plt.xlim(0, 5) plt.ylim(0, 35) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.show() Output What is Seaborn? Seaborn is a Python data visualization library that operates as an abstraction layer over Matplotlib. It”s designed to create visually appealing and informative statistical graphics, simplifying the process of generating complex visualizations from data. The following are the key features of the seaborn library. Statistical Data Visualization Seaborn is built on top of Matplotlib and is particularly well-suited for statistical data visualization. It simplifies the process of creating complex plots by providing high-level abstractions. Default Aesthetics Seaborn comes with attractive default styles and color palettes that make plots aesthetically pleasing with minimal effort. Specialized Plots It specializes in certain types of plots like violin plots, box plots, pair plots and more which are easier to create in Seaborn compared to Matplotlib. Basic seaborn plot The following is the basic seaborn line plot. Example import seaborn as sns import matplotlib.pyplot as plt # Sample data x_values = [1, 2, 3, 4, 5] y_values = [2, 4, 6, 8, 10] # Creating a line plot using Seaborn sns.lineplot(x=x_values, y=y_values) plt.show() Output Matplotlib Seaborn Level of Abstraction Matplotlib is more low-level and requires more code for customizations. Seaborn abstracts some complexities by enabling easier creation of complex statistical plots. Default Styles Matplotlib doesn’t have better default styles and color palettes when compared to seaborn. Seaborn has better default styles and color palettes by making its plots visually appealing without much customization. Specialized Plots Matplotlib require more effort to plot certain plots readily. Seaborn offers certain types of plots that are not readily available or require more effort in Matplotlib. When to use each library We can use this library when we need fine-grained control over the appearance of our plots or when creating non-standard plots that may not be available in other libraries. We can use this library when working with statistical data especially for quick exploration and visualization of distributions, relationships and categories within the data. Seaborn”s high-level abstractions and default styles make it convenient for this purpose. Both libraries are valuable in their own way and sometimes they can be used together to combine the strengths of both for advanced visualization tasks. Print Page Previous Next Advertisements ”;