Matplotlib – Pie Chart ”; Previous Next A Pie Chart can only display one series of data. Pie charts show the size of items (called wedge) in one data series, proportional to the sum of the items. The data points in a pie chart are shown as a percentage of the whole pie. Matplotlib API has a pie() function that generates a pie diagram representing data in an array. The fractional area of each wedge is given by x/sum(x). If sum(x)< 1, then the values of x give the fractional area directly and the array will not be normalized. Theresulting pie will have an empty wedge of size 1 – sum(x). The pie chart looks best if the figure and axes are square, or the Axes aspect is equal. Parameters Following table lists down the parameters foe a pie chart − x array-like. The wedge sizes. labels list. A sequence of strings providing the labels for each wedge. Colors A sequence of matplotlibcolorargs through which the pie chart will cycle. If None, will use the colors in the currently active cycle. Autopct string, used to label the wedges with their numeric value. The label will be placed inside the wedge. The format string will be fmt%pct. Following code uses the pie() function to display the pie chart of the list of students enrolled for various computer language courses. The proportionate percentage is displayed inside the respective wedge with the help of autopct parameter which is set to %1.2f%. from matplotlib import pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.axis(”equal”) langs = [”C”, ”C++”, ”Java”, ”Python”, ”PHP”] students = [23,17,35,29,12] ax.pie(students, labels = langs,autopct=”%1.2f%%”) plt.show() Print Page Previous Next Advertisements ”;
Category: matplotlib
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
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 – Artists
Matplotlib – Artists ”; Previous Next Understanding Artists in Matplotlib In Matplotlib, almost everything you see on a plot is an instance of an Artist, which are objects that represent various components of a plot. Whether it”s a line representing data, a text label, or even the tick marks on an axis, everything in a Matplotlib plot is an Artist object. Before exploring the Artist hierarchy, let’s observe the below image to understand the basic components of a figure in matplotlib − In the figure, each element, such as lines and points that represent data, along with minor ticks and points associated text labels, can be identified as individual Artist objects. Artist Hierarchy In matplotlib”s hierarchy, Artists can be broadly categorized into two types − Primitive Artists − These are the basic building blocks of a plot. Examples include Line2D, Rectangle, Text, AxesImage, and more. These are the standard graphical objects that we want to paint onto our canvas. Composite Artists − These are higher-level structures that contain other Artists. Examples include Figure, Axis, and Axes. A Figure is like a canvas that holds everything, while Axes represents a specific plot within the figure. Creating and Accessing the Artists Artists are typically created through plotting methods on an Axes object. These methods not only facilitate the creation of visual elements but also return specific artist instances corresponding to the plotted elements. Below are some common plotting methods and the corresponding artists they generate − annotate − Generates an Annotation artist for text annotations. bar − Creates a Rectangle artist for bar charts. errorbar − Produces Line2D and Rectangle artists for error bar plots. fill − Generates a Polygon artist for shared areas. hist − Creates Rectangle artists for histograms. imshow − Generates an AxesImage artist for image data. legend − Produces a Legend artist for Axes legends. plot − Creates Line2D artists for XY plots. Returns a list when multiple datasets are plotted. scatter − Generates a PolyCollection artist for scatter charts. text − Produces a Text artist for displaying text on the plot. Example Let”s see an example for creating and accessing the artists using the plot() method. import matplotlib.pyplot as plt import matplotlib.artist as martist import numpy as np # Create a subplot fig, ax = plt.subplots() # Generate random data x, y = np.random.rand(2, 100) # Use the plot method to create a Line2D artist lines = ax.plot(x, y, ”-”, label=”example”) # Accessing the Line2D artists created by the plot method print(”Line2D artists created by the plot method:”, lines) # Retrieve all Line2D artists associated with the Axes lines_on_axes = ax.get_lines() # Display the retrieved Line2D artists print(”Line2D artists obtained using get_lines():”, lines_on_axes) # Accessing the first (and in this case, the only) Line2D artist print(”Accessing the first Line2D artist”, ax.get_lines()[0]) Output On executing the above code we will get the following output − Line2D artists created by the plot method: [<matplotlib.lines.Line2D object at 0x000001DB3666A620>] Line2D artists obtained using get_lines(): Accessing the first Line2D artist Line2D(example) Modifying the Artists Properties Artists have various properties that define their appearance and behavior. These properties include color, linestyle, linewidth, and markers. Modifying these properties enables us to control the visual aspects of the plot. Example The following example demonstrates how to create a simple plot and then modify the properties of the associated Line2D artist. import matplotlib.pyplot as plt import numpy as np # Creating a simple plot fig, ax = plt.subplots(figsize=(7, 4)) x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) # Use the plot method to create a Line2D artist lines = ax.plot(x, y) # Displaying initial properties of the Line2D artist print(”Initial properties of the Line2D artist:”) print(”Color:”, ax.get_lines()[0].get_color()) print(”Line Style:”, ax.get_lines()[0].get_linestyle()) print(”Marker Size:”, ax.get_lines()[0].get_markersize()) # Modifying properties lines[0].set(color=”green”, linewidth=2) lines[0].set_linestyle(”:”) lines[0].set_marker(”s”) lines[0].set_markersize(10) # Accessing the modified properties of the Line2D artist print(”nModified properties of the Line2D artist:”) print(”Color:”, ax.get_lines()[0].get_color()) print(”Line Style:”, ax.get_lines()[0].get_linestyle()) print(”Marker Size:”, ax.get_lines()[0].get_markersize()) Output On executing the above code we will get the following output − Initial properties of the Line2D artist: Color: #1f77b4 Line Style: - Marker Size: 6.0 Modified properties of the Line2D artist: Color: green Line Style: : Marker Size: 10.0 Manipulating Artist Data Beyond styling properties, artists may also contain data. For example, the Line2D object has a data property that can be modified using the set_data() method. Example Here is an example that manipulate artist data. import matplotlib.pyplot as plt import numpy as np # Creating a simple plot fig, ax = plt.subplots(figsize=(7, 4)) x = np.linspace(0, 2 * np.pi, 100) # Initial sinusoidal curve y = np.sin(x) # Use the plot method to create a Line2D artist a sinusoidal curve lines = ax.plot(x, y) # Modifying the artist data with the cosine lines[0].set_data([x, np.cos(x)]) # Displaying the plot plt.show() Output On executing the above code we will get the following output − Manual Addition of Artists While many artists have helper methods, there are scenarios where manual addition is necessary. For instance, adding patches like circles or rectangles directly to an Axes object can be possible by using the add_artist() method. Example In this example, we manually add circle patches to the axes. import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as mpatches # Creating a simple plot fig, ax = plt.subplots(figsize=(7, 4)) x = np.linspace(0, 2 * np.pi, 100) # Initial sinusoidal curve y = np.sin(x) # Use the plot method to create a Line2D artist for a sinusoidal curve
Matplotlib – Create Logo
Matplotlib – Create Logo ”; Previous Next Creating a logo generally means designing a unique symbol or image that represents a brand, company, product, or organization. It involves combining visual elements like shapes, colors, and text to convey the identity and message of the entity it represents. Create Logo in Matplotlib You can create a logo in Matplotlib using the library”s plotting functionalities to design a visual symbol or image that represents a brand, company, product, or organization. Similar to other plotting tasks, creating a logo in Matplotlib requires combining various graphical elements such as shapes, colors, text, and possibly images to craft a unique and recognizable emblem. Simple Geometric Logo A simple geometric logo in Matplotlib refers to creating a basic graphical representation using geometric shapes like squares, circles, triangles, or lines. You can use functions like plt.plot(), plt.scatter(), plt.fill(), or plt.text() to draw various geometric shapes and add text to your plot. By combining these elements and arranging them creatively, you can design a simple logo for your project, brand, or visualization. Example In the following example, we create a simple circular logo using Matplotlib. We use the Circle() function to draw a blue-colored circle and add it to the plot using the add_artist() function. We then turn off the axes, and set the aspect ratio to ensure the circle appears round − import matplotlib.pyplot as plt # Creating a circle circle = plt.Circle((0.5, 0.5), 0.4, color=”blue”) # Creating the plot fig, ax = plt.subplots() ax.add_artist(circle) # Customizing the plot ax.set_aspect(”equal”) ax.axis(”off”) # Displaying the logo plt.show() Output Following is the output of the above code − Creating a Text Logo A text logo in Matplotlib involves creating a logo or visual representation using text elements. Instead of relying on geometric shapes or images, a text logo uses characters and symbols to convey a brand or identity. In Matplotlib, you can use the plt.text() function to add text to your plot. This function allows you to specify the position, text content, font size, color, and other properties of the text you want to display. Example In here, we create a text-based logo using Matplotlib. We use the text() function to place the word “Logo” at the center of the plot with “red” color and customized font size − import matplotlib.pyplot as plt # Creating text text = plt.text(0.5, 0.5, ”Logo”, fontsize=50, color=”red”, ha=”center”, va=”center”) # Customizing the plot plt.axis(”off”) # Displaying the logo plt.show() Output On executing the above code we will get the following output − Creating a Complex Shape Logo A complex shape logo in Matplotlib refers to creating a logo using intricate or detailed shapes, patterns, and designs. Unlike simple geometric logos, which rely on basic shapes like squares, circles, or triangles, complex shape logos often involve more elaborate and intricate elements. In Matplotlib, you can combine various plotting functions, such as plt.plot(), plt.fill(), plt.scatter(), and plt.polygon(), to create complex shapes and patterns. By carefully arranging these elements and applying different colors, styles, and transformations, you can design intricate logos that convey a unique brand identity or message. Complex shape logos can include a wide range of elements, such as curves, curves, arcs, polygons, and other geometric shapes. They may also consist of text, images, or other visual elements. Example Now, we create a logo with a complex shape by combining an ellipse, a polygon, and a star. We create each shape the Ellipse and Polygon classes, respectively. We then use the add_artist() function to add each shape to the plot − import matplotlib.pyplot as plt from matplotlib.patches import Ellipse, Polygon # Creating an ellipse ellipse = Ellipse((0.5, 0.5), width=0.7, height=0.4, angle=45, color=”orange”) # Creating a polygon vertices = [[0.2, 0.4], [0.8, 0.4], [0.6, 0.8], [0.4, 0.8]] polygon = Polygon(vertices, closed=True, color=”blue”) # Creating a star star_vertices = [[0.3, 0.6], [0.4, 0.9], [0.5, 0.6], [0.6, 0.9], [0.7, 0.6], [0.5, 0.4], [0.3, 0.6]] star = Polygon(star_vertices, closed=True, color=”green”) # Creating the plot fig, ax = plt.subplots() ax.add_artist(ellipse) ax.add_patch(polygon) ax.add_patch(star) # Customizing the plot ax.set_aspect(”equal”) ax.axis(”off”) # Displaying the logo plt.show() Output After executing the above code, we get the following output − Creating an Image Logo An image logo in Matplotlib refers to using an image or picture as a logo in a plot. Instead of creating shapes, lines, or text to form a logo, you can insert an existing image file, such as a PNG, JPEG, or GIF, into your Matplotlib plot. To add an image logo to a Matplotlib plot, you can use the plt.imshow() function, which displays an image on the plot. You will first need to load the image file and then pass the image data to plt.imshow() to display it within your plot. Example In the following example, we create a logo using an external image file with Matplotlib. We load the image using the imread() function and then display it using the imshow() function − import matplotlib.pyplot as plt import matplotlib.image as mpimg # Loading image img = mpimg.imread(”tutorialspoint_logo.png”) # Displaying image plt.imshow(img) plt.axis(”off”) # Displaying the logo plt.show() Output On executing the above code we will get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Grids
Matplotlib – Grids ”; Previous Next In general data visualization and plotting, grids refer to the set of horizontal and vertical lines over the plot area. Gridlines are useful for a better understanding of the data on the plots. Typically, these lines are aligned with the major tick marks on both the x-axis and the y-axis. They can enhance the readability of the plot and make it easier to estimate values. See the below image for reference − There are two main types of gridlines − Major Gridlines − These are the primary gridlines that align with the major tick marks on the axes. Minor Gridlines − These are additional gridlines between the major gridlines and align with the minor tick marks on the axes. Introduction to Grids in Matplotlib Enabling gridlines is a straightforward process in Matplotlib. The pyplot.grid() method adds major gridlines to the plot with additional customization options including adjusting the linestyle, linewidth, color, and transparency. Let”s explore different approaches to adding gridlines to plots. Basic Plot with Grids In Matplotlib, the default grid is a set of major gridlines that align with the major tick marks on both the x-axis and the y-axis. Example In this example, we create a basic sine wave plot and add the default grid. import matplotlib.pyplot as plt import numpy as np # Create some data x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) # create a plot fig, ax = plt.subplots(figsize=(7,4)) # Plot the data plt.plot(x, y) # Add grid ax.grid(True) # set the title ax.set_title(”Basic Plot with Grids”) # Show the plot plt.show() Output On executing the above code we will get the following output − Customizing Grid Customizing gridlines includes linestyle, linewidth, color, and transparency. Example This example demonstrates how to customize the gridline by changing its linestyle, linewidth, color, and transparency. import matplotlib.pyplot as plt import numpy as np # Create some data x = np.arange(0, 1, 0.05) y = x**2 # Create the plot fig, ax = plt.subplots(figsize=(7,4)) # Plot the data plt.scatter(x, y) # Customize grid ax.grid(True, linestyle=”-.”, linewidth=1, color=”red”, alpha=0.9) # set the title ax.set_title(”Customizing Grids”) # Show the plot plt.show() Output On executing the above code we will get the following output − Adding Minor Gridlines In addition to major gridlines, Matplotlib supports the inclusion of minor gridlines. These are the lines positioned between the major gridlines and aligning with the minor tick marks on both the x-axis and the y-axis. You can use the pyplot.minorticks_on() and plt.grid(which=”minor”) to add gridlines corresponding to the minor ticks. Example This example demonstrates how to add both the major and minor gridlines to a plot. import matplotlib.pyplot as plt import numpy as np # Create some data x = np.arange(0, 1, 0.05) y = x**2 # Create the plot fig, ax = plt.subplots(figsize=(7,4)) # Plot the data plt.scatter(x, y) # Add major grid ax.grid(True) # Add minor grid ax.minorticks_on() ax.grid(which=”minor”, linestyle=”:”, linewidth=0.5, color=”red”, alpha=0.5) # set the title ax.set_title(”Major and Minor Gridlines”) # Show the plot plt.show() Output On executing the above code we will get the following output − Manually adding the grids This approach involves explicitly specifying the positions of vertical and horizontal lines. By iterating through specific intervals or values, users can draw gridlines at desired locations. This involves using functions like pyplot.axvline() and pyplot.axhline() to draw vertical and horizontal lines, respectively. Example Here is an example that manually draws vertical grid lines at every third point on the x-axis. import matplotlib.pyplot as plt import numpy as np # Create some data x = np.arange(0, 1, 0.05) y = x**2 # Create the plot plt.subplots(figsize=(7,4)) # Plot the data plt.scatter(x, y) # Set x and y tick locations plt.xticks(np.arange(0, 1.01, 0.1)) plt.yticks(np.arange(0, 1.01, 0.1)) plt.title(”Manually Drawing the Grids ”) # Draw grid lines for every third point on the x-axis for pt in np.arange(0, 1.01, 0.3): plt.axvline(pt, lw=0.5, color=”black”, alpha=0.5) # Show the plot plt.show() Output On executing the above code we will get the following output − Hiding the gridlines Hiding or removing the gridlines in a plot can be achieved by specifying the boolean value False to the grid() function. Example Here is an example that hide gridlines and axes (X and Y axis) of a plot. import numpy as np import matplotlib.pyplot as plt # Create a figure fig = plt.figure(figsize=(7, 4)) # Generate data x = np.linspace(-10, 10, 50) y = np.sin(x) # Plot horizontal line plt.axhline(y=0, c=”green”, linestyle=”dashdot”, label=”y=0″) # Plot sine curve plt.plot(x, y, c=”red”, lw=5, linestyle=”dashdot”, label=”y=sin(x)”) # Hide gridlines plt.grid(False) # Hide axes plt.axis(”off”) # Add legend plt.legend() # Show plot plt.show() Output On executing the above code you will get the following output − Gridlines Across The Subplots When comparing data across multiple subplots, it”s useful to have gridlines across all subplots to maintain visual comparisons between plots. Example Here is an example that demonstrates how to plot grids across subplots. import matplotlib.pyplot as plt # Data d = [1, 2, 3, 4, 5, 6, 7, 8, 9] f = [0, 1, 0, 0, 1, 0, 1, 1, 0] # Create figure and subplots fig = plt.figure(figsize=(7,4)) fig.set_size_inches(30, 10) ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) # Plot data on subplots ax1.plot(d, marker=”.”, color=”b”, label=”1 row”) # Draw grid lines behind bar graph ax2.bar(range(len(d)), d, color=”red”, alpha=0.5) # Enable grids on both subplots ax1.grid() ax2.grid() # Display the plot plt.show() Output On executing the above code you will get the following output − Print Page Previous Next Advertisements ”;
Matplotlib – Transforms
Matplotlib – Transforms ”; Previous Next Transform in general is a way to change something from one form to another. It is like taking an input and turning it into a different output. Transforms are used in various fields, such as mathematics, physics, and computer science. For example, in mathematics, a transform can be a mathematical operation that changes a set of numbers or functions into a different representation. The Fourier transform, for instance, converts a function in the time domain (like a sound wave) into its frequency components. Transforms in Matplotlib In Matplotlib, transforms refer to the conversion process from data coordinates to pixel coordinates, allowing to place the graphical elements such as points, lines, and text within a plot accurately. You can use various types of transformations in matplotlib, such as linear transformations, logarithmic transformations, and more. To handle these transformations, Matplotlib provides the “transform” parameter. The “transform” parameter can take various values, such as instances of the “matplotlib.transforms.Transform” class or strings representing common transformations like ”ax.transData” for data coordinates or ”ax.transAxes” for axes coordinates. By using the transform parameter, you can customize the coordinate system and apply different transformations to enhance the visualization of their data on the Matplotlib plots. Data to Axes Transform In Matplotlib, the data to axes transform refers to the process of converting your actual data points into coordinates within the axes of your plot. When you plot data, you use specific “x” and “y” values. The transformation ensures that these data points are correctly positioned within the axes of your plot, taking into account the scaling and limits of the “x” and “y” axes. Example In the following example, we are creating a simple line plot using data coordinates (x, y). We then use the ax.text() function to add text to the plot, specifying the position (2, 25) in data coordinates. The “transform=ax.transData” parameter ensures that the text is positioned using data coordinates − import matplotlib.pyplot as plt # Data x = [1, 2, 3, 4] y = [10, 20, 25, 30] # Creating a plot fig, ax = plt.subplots() ax.plot(x, y, marker=”o”, linestyle=”-”, label=”Data points”) ax.legend() # Transforming data coordinates to axes coordinates ax.text(2, 25,”Text in Data Coordinates” , transform=ax.transData) # Setting plot title and labels ax.set_title(”Data to Axes Transform”) ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) plt.show() Output Following is the output of the above code − Axes to Data Transform The axes to data transform in Matplotlib is the reverse of the “data to axes transform”. While the “data to axes transform” converts your actual data points into coordinates within the axes of your plot, the “axes to data transform” does the opposite. It takes coordinates specified in terms of the axes of your plot and converts them into the corresponding data values. Example In here, we are creating a plot with axis limits set between “0” and “1” for both “x” and “y” axes. We use the ax.text() function to add text to the plot, specifying the position “(0.5, 0.5)” in axes coordinates. The “transform=ax.transAxes” parameter ensures that the text position is interpreted as relative to the axes rather than the data − import matplotlib.pyplot as plt # Creating a plot with normalized axes fig, ax = plt.subplots() ax.set_xlim(0, 1) ax.set_ylim(0, 1) # Transforming axes coordinates to data coordinates ax.text(0.5, 0.5, ”Text in Axes Coordinates”, transform=ax.transAxes, ha=”center”, va=”center”) # Setting plot title and labels ax.set_title(”Axes to Data Transform Example”) ax.set_xlabel(”X-axis (normalized)”) ax.set_ylabel(”Y-axis (normalized)”) plt.show() Output On executing the above code we will get the following output − Blended Transform In Matplotlib, a blended transform is a way to combine or blend different coordinate systems when placing elements on a plot. It allows you to create a custom transformation that contains aspects of both data coordinates and axes coordinates. Example In the example below, we are creating a plot and using the blended_transform_factory() function to create a blended transformation. The resulting “trans” object is a blend of both data and axes coordinates. The ax.text() function then uses this blended transformation to position text at (0.8, 0.2), effectively combining data and axes coordinates − import matplotlib.pyplot as plt from matplotlib.transforms import blended_transform_factory # Creating a plot fig, ax = plt.subplots() # Creating a blended transformation trans = blended_transform_factory(ax.transData, ax.transAxes) # Adding text using the blended transformation ax.text(0.8, 0.2, ”Blended Transform”, transform=trans, ha=”center”, va=”center”) # Setting plot title and labels ax.set_title(”Blended Transform”) ax.set_xlabel(”X-axis”) ax.set_ylabel(”Y-axis”) plt.show() Output After executing the above code, we get the following output − Offset Transform In Matplotlib, an offset transform is a way to add a precise offset to the position of elements on a plot. It involves shifting or translating the coordinates of the elements by a specified amount. This type of transformation is useful when you want to fine-tune the placement of text, markers, or other graphical elements. For example, if you have a data point at (2, 10) and you want to display a label slightly to the right and above this point, you can use an Offset Transform to apply a specific offset to the original coordinates. This allows you to control the exact positioning of elements relative to their original locations in the data. Example Now, we are creating a plot, and using the “ScaledTranslation” class to create an offset transformation. The “trans” object is a combination of the original data transformation (ax.transData) and a scaled translation of (0.1, 0.2) in data coordinates. The ax.text() function then uses this transformed coordinate to position text at (2, 25) with the specified offset − import matplotlib.pyplot as plt from matplotlib.transforms import ScaledTranslation # Creating a plot fig, ax = plt.subplots() # Creating an offset transformation trans =
Matplotlib – Formatting Axes
Matplotlib – Formatting Axes ”; Previous Next What is Formatting Axes? Formatting axes in Matplotlib involves customizing various aspects of the plot”s axes such as ticks, labels, scale, limits and more. This customization enhances the readability and presentation of the data visualization. Formatting the axes in Matplotlib allows us to tailor the visualization according to our data”s characteristics and presentation requirements. Experiment with various formatting options to create clear and informative plots. Use Cases The following are the use cases of Formatting Axes. Enhancing Readability − Adjust font sizes, colors and labels for better visualization. Data Emphasis − Set limits and scale to focus on specific data ranges. Aesthetics − Customize appearance with titles, grid lines and spine properties. Clarity and Context − Label axes and add titles for understanding the plot”s content. Axes Formatting Options We have different Axes formatting options let’s go through each and everyone in detail. Ticks and Tick Labels In Matplotlib ticks are the small marks on an axis that denote specific data points and where as tick labels are the values corresponding to those ticks. We can customize their appearance using various functions in Matplotlib. To modify ticks and tick labels we can use methods like plt.xticks() and plt.yticks() to set their positions and labels. plt.xticks() and plt.yticks() allow us to set the locations and labels of ticks on the x and y axes respectively. We can adjust the appearance of ticks using plt.tick_params() to change aspects like size, color, direction etc. Formatting the tick labels can be done through plt.gca().xaxis or plt.gca().yaxis with methods like set_major_formatter() to control their display such as scientific notation, decimal places, date format and etc. Additionally for more granular control we can access specific ticks and labels using ax.get_xticks(), ax.get_yticks(), ax.get_xticklabels(), ax.get_yticklabels() and then modify them individually. Example In this example we are setting the ticks and tick labels of a plot with the use of above discussed functions and methods available in matplotlib library. import matplotlib.pyplot as plt import numpy as np # Generating sample data x = np.linspace(0, 10, 100) y = np.sin(x) # Creating a plot plt.figure(figsize=(8, 5)) plt.plot(x, y) # Customizing ticks and tick labels plt.xticks(np.arange(0, 11, 2)) # Set x-axis ticks at intervals of 2 plt.yticks(fontsize=10, color=”red”) # Customize y-axis tick labels (font size and color) plt.xlabel(”X-axis”, fontsize=12) plt.ylabel(”Y-axis”, fontsize=12) plt.title(”Ticks and Tick Labels Formatting”, fontsize=14) plt.show() Output On executing the above code we will get the following output − Axis Limits and Scale Axis limits and scale are fundamental aspects when creating visualizations. They control the range and appearance of the data displayed along the axes of a plot or chart. Axis Limits The Axis limits define the span of values shown on each axis. By setting limits we can focus on a specific range of data by emphasizing particular details or trends. For example in a scatter plot if we set axis limits then it can zoom in on a particular region of interest. Scale The scale determines how the data is distributed and represented along an axis. Common scales include linear, logarithmic and categorical. Linear scale represents data equally spaced along the axis where as logarithmic scale emphasizes changes in orders of magnitude and categorical scale is used for non-numeric data or categories. Here are key considerations and actions related to axis limits and scale. Setting Limits − Define the minimum and maximum values for each axis to control what portion of the data is displayed. Zooming In/Out − Adjust axis limits to focus on specific data ranges or zoom out to show the overall context. Scale Transformation − Changing the scale type can alter how the data is perceived. For instance by using a logarithmic scale can better visualize exponential growth or wide-ranging data. Normalization − Normalize data if needed to bring different scales into a comparable range especially when plotting multiple datasets on the same graph. Limiting Outliers − Set axis limits to exclude outliers or anomalies by providing a clearer view of the main data distribution. Scale Customization − Some visualization libraries allow customization of scale aesthetics such as tick placement and labeling for different scales. In Python libraries like Matplotlib or Seaborn provide functionalities to manipulate axis limits and scales by allowing user for detailed control over how data is presented in plots. Example Here”s an example using Python”s Matplotlib library to demonstrate setting axis limits and changing scales. import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0.1, 100, 500) y = np.sin(x) # Creating a figure and axes object fig, axs = plt.subplots(1, 2, figsize=(12, 5)) # Plot with default linear scale axs[0].plot(x, y) axs[0].set_title(”Linear Scale”) # Plot with logarithmic scale for the y-axis axs[1].plot(x, y) axs[1].set_yscale(”log”) # Set logarithmic scale for the y-axis axs[1].set_title(”Logarithmic Scale (y-axis)”) plt.tight_layout() plt.show() Output On executing the above code we will get the following output − Axis Labels and Titles Axis labels and titles are crucial components of any visualization in providing context and information about the data represented on the plot. They help readers understand what each axis represents and the overall purpose of the visualization. Customizing axis labels and titles involves specifying text, adjusting font size, setting font weight, changing color and positioning them appropriately within the plot to ensure clarity and readability. Axis Labels The Axis labels describe the quantity or nature of the data displayed along each axis. For example in a scatter plot with height on the y-axis and weight on the x-axis, the labels might be “Height (cm)” and “Weight (kg)”. They make it clear what the plotted values signify. Titles
Matplotlib – Subplot2grid() Function ”; Previous Next This function gives more flexibility in creating an axes object at a specific location of the grid. It also allows the axes object to be spanned across multiple rows or columns. Plt.subplot2grid(shape, location, rowspan, colspan) In the following example, a 3X3 grid of the figure object is filled with axes objects of varying sizes in row and column spans, each showing a different plot. import matplotlib.pyplot as plt a1 = plt.subplot2grid((3,3),(0,0),colspan = 2) a2 = plt.subplot2grid((3,3),(0,2), rowspan = 3) a3 = plt.subplot2grid((3,3),(1,0),rowspan = 2, colspan = 2) import numpy as np x = np.arange(1,10) a2.plot(x, x*x) a2.set_title(”square”) a1.plot(x, np.exp(x)) a1.set_title(”exp”) a3.plot(x, np.log(x)) a3.set_title(”log”) plt.tight_layout() plt.show() Upon execution of the above line code, the following output is generated − Print Page Previous Next Advertisements ”;