Matplotlib – Basemap ”; Previous Next What is Basemap? The Matplotlib Basemap toolkit is an extension to Matplotlib that provides functionality for creating maps and visualizations involving geographical data. It allows users to plot data on various map projections, draw coastlines, countries and other map features . These are used to handle geographic coordinates seamlessly within Matplotlib. The below are the key features of Matplotlib Basemap. Map Projections Basemap supports various map projections by allowing users to visualize data in different coordinate systems like cylindrical, conic or azimuthal projections. Examples are Mercator, Lambert Conformal Conic and Orthographic projections. Plotting Geographic Data Basemap allows the plotting of geographical data such as points, lines, or polygons over maps. Users can overlay datasets onto maps and visualize geographic relationships. Map Elements Basemap provides functions to add map elements like coastlines, countries, states, rivers and political boundaries by enhancing the visual context of the maps. Coordinate Transformation It facilitates seamless conversion between different coordinate systems such as latitude and longitude to map projection coordinates and vice versa. Installing Basemap If we want to work with Basemap of matplotlib library we have to install it in our working environment. The below is the code. Example pip install basemap Note − When we are working with Jupyter notebook then we have to install basemap through the anaconda command terminal. Output Basic Workflow with Basemap The below is the basic workflow of the Basemap of the Matplotlib library. Let’s see each of them in detail for better understanding. Create a Basemap Instance Instantiate a Basemap object by specifying the map projection, bounding coordinates and other parameters. To create a Basemap instance using the Basemap toolkit in Matplotlib we can define the map projection and specify the desired map boundaries. Example In this example we are generating a basic map with coastlines and country boundaries using the specified Mercator projection and the provided bounding coordinates. We can further customize the map by adding features, plotting data points or using different projections and resolutions based on our requirements. from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt # Create a Basemap instance with a specific projection and bounding coordinates map = Basemap( projection=”merc”, llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180, resolution=”c”) # Draw coastlines and countries map.drawcoastlines() map.drawcountries() # Show the map plt.show() Output Plot Data on the Map In this we use the Basemap methods to draw map features, plot data points or visualize geographical datasets. Example In this example we are generating random latitude and longitude points and then uses the map() function to project these coordinates onto the Basemap instance. The scatter() method is then used to plot these projected points on the map as red markers. from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np # Create a Basemap instance with a specific projection and bounding coordinates map = Basemap( projection=”merc”, llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180, resolution=”c”) # Draw coastlines and countries map.drawcoastlines() map.drawcountries() # Generate random data (longitude, latitude) for plotting num_points = 100 lons = np.random.uniform(low=-180.0, high=180.0, size=num_points) lats = np.random.uniform(low=-80.0, high=80.0, size=num_points) # Plot the data points on the map x, y = map(lons, lats) # Project the latitudes and longitudes to map coordinates map.scatter(x, y, marker=”o”, color=”red”, zorder=10) # Plotting the data points # Show the map with plotted data plt.title(”Data Points on Map”) plt.show() Output Display the Map We can use Matplotlib library to show() function to display the final map. Example Here”s an example demonstrating the usage of Basemap to create a map and plot data points. from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np # Creating a Basemap instance with a specific projection and bounding coordinates map = Basemap( projection=”merc”, llcrnrlat=-80, urcrnrlat=80, llcrnrlon=-180, urcrnrlon=180, resolution=”c”) # Drawing coastlines, countries, and states map.drawcoastlines() map.drawcountries() map.drawstates() # Generating random data for plotting num_points = 100 lons = np.random.uniform(low=-180.0, high=180.0, size=num_points) lats = np.random.uniform(low=-80.0, high=80.0, size=num_points) data_values = np.random.rand(num_points) * 100 # Random values for data # Plotting data points on the map x, y = map(lons, lats) # Projecting latitudes and longitudes to map coordinates map.scatter(x, y, c=data_values, cmap=”viridis”, marker=”o”, alpha=0.7) # Adding a colorbar to represent the data values plt.colorbar(label=”Data Values”) # Display the map with plotted data plt.title(”Basemap Example with Data Points”) plt.show() Output Applications of Matplotlib Basemap Geospatial Analysis − Analyzing and visualizing geographical data such as climate patterns, population distributions or seismic activities. Cartography − Creating custom maps for publications, presentations or research purposes. Data Visualization − Integrating geographical data with other datasets for exploratory data analysis. Note Matplotlib Basemap is being phased out in favor of newer geospatial libraries like Cartopy which offer more extensive functionality and better integration with Matplotlib. Cartopy builds on the concepts of Basemap but provides a more modern, flexible and actively developed interface for handling geospatial data within Matplotlib. Print Page Previous Next Advertisements ”;
Category: matplotlib
Matplotlib – PostScript
Matplotlib – PostScript ”; Previous Next PostScript is a page description language and a dynamically typed, stack-based programming language often abbreviated as PS. Created by Adobe Systems in the early 1980s, its primary purpose is to describe the layout and graphics of printed pages. It is widely used in electronic publishing and desktop publishing applications. A PostScript file can be printed or displayed on different devices without losing quality. This is the key advantage when generating plots for different purposes. PostScript in Matplotlib In the context of Matplotlib, PostScript serves as a backend rendering engine (used for displaying figures on the screen or writing to files), enabling users to generate publication-quality plots and graphics. When you choose the PostScript backend, Matplotlib generates PostScript code to describe the layout and appearance of the plot. The PostScript code generated by Matplotlib includes instructions for drawing lines, shapes, text, and other graphical elements on a page. These instructions are written in the PostScript programming language. The Matplotlib PostScript Backend (matplotlib.backends.backend_ps) can produce both .ps and .eps files. Create a PostScript file Let”s explore how to create a simple plot and save it as a PostScript file using Matplotlib. Example 1 This example demonstrates how to create a simple plot with wrapped text and saves it as a PostScript file(.ps). import matplotlib import matplotlib.pyplot as plt import textwrap from pylab import * # Generate a string containing printable characters (ASCII 32 to 126) text_to_wrap = “”.join(c for c in map(chr, range(32, 127)) if c.isprintable()) # Wrap the string to fit within the figure wrapped_text = “n”.join(textwrap.wrap(text_to_wrap)) # Add the wrapped text to the figure figtext(0, 0.5, wrapped_text) # Save the figure to a PostScript file named “test.ps” savefig(“test.ps”) print(”Successfully created the PostScript (PS) file…”) Output If you visit the folder where the Output is saved you can observe resultant PostScript file named test.ps. Successfully created the PostScript (PS) file… Example 2 Here is another example that demonstrates how to use the PostScript backend to generate a plot and save it to an encapsulated PostScript (EPS) file. import numpy as np from matplotlib import pyplot as plt # Generate data x_data = np.linspace(1, 10, 100) y_data = np.sin(x_data) # Create the plot plt.plot(x_data, y_data, c=”green”, marker=”o”) plt.grid() # Save the figure to a PostScript file named “example.eps” plt.savefig(“example.eps”) print(”Successfully created the encapsulated PostScript (EPS) file…”) Output If you visit the folder where the Output is saved you can observe resultant PostScript file named example.eps. Successfully created the encapsulated PostScript (EPS) file… Customizing PostScript Output Adjusting the PostScript output settings in Matplotlib allows you to enhance the visual quality of Encapsulated PostScript (EPS) files. By default, Matplotlib uses a distillation process when creating EPS files. This distillation step removes specific PostScript operators that LaTeX considers illegal in an EPS file. One effective workaround involves modifying the resolution parameter to achieve better visual results. The rcParams[“ps.distiller.res”] parameter controls the resolution of the EPS files, with the default value set to 6000. Increasing this value can result in larger files but may significantly improve visual quality and maintain reasonable scalability. Example 1 This example demonstrates how adjusting resolution parameter can enhance the visual quality of EPS files. import numpy as np import matplotlib.pyplot as plt # Set the resolution for EPS files plt.rcParams[“ps.distiller.res”] = 12000 # Set the figure size and enable autolayout plt.rcParams[“figure.figsize”] = [7, 3.50] plt.rcParams[“figure.autolayout”] = True # Generate data x_data = np.linspace(1, 10, 100) y_data = np.sin(x_data) # Plotting plt.plot(x_data, y_data, label=”Sine Wave”, color=”green”) # Save the figure as an EPS file plt.savefig(”Output customized file.eps”, format=”eps”, bbox_inches=”tight”) print(”Successfully created the output customized PostScript (EPS) file…”) Output If you visit the folder where the Output is saved you can observe resultant PostScript file named Output customized file.eps. Successfully created the output customized PostScript (EPS) file… Example 2 Here is an example that demonstrates how the transparency is preserved when saving the plot as an .eps file by setting the transparent=True parameter in the savefig() function. import numpy as np import matplotlib.pyplot as plt # Adjust figure size and autolayout plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True # Generate data x_data = np.linspace(1, 10, 100) y_data = np.sin(x_data) # Plot data with transparency plt.plot(x_data, y_data, c=”green”, marker=”o”, alpha=.35, ms=10, lw=1) plt.grid() # Save plot as .eps by preserving the transparency plt.savefig(“lost_transparency_img.eps”, transparent=True) # Display plot plt.show() Output On executing the above code you will get the following output − Whenever plots are saved in .eps/.ps, then the transparency of the plots get lost. You can observe the difference in th eabove image. Print Page Previous Next Advertisements ”;
Matplotlib – Ribbon Box
Matplotlib – Ribbon Box ”; Previous Next In general, a “ribbon box” is a graphical representation used to visualize data distributions across different categories or groups. The term “ribbon box” refers to a specific type of plot that displays these distributions in a visually appealing and informative manner. It is particularly useful when you have multiple categories or groups and want to compare the distributions of a variable across these categories. In a ribbon box plot − Each category or group is typically represented along the x-axis. The y-axis often represents the range or distribution of a numeric variable. Each “ribbon” corresponds to the distribution of the numeric variable within a particular category or group. The ribbon can be shaded or colored to indicate the density or intensity of the distribution within each category. This allows for easy comparison of distributions across different categories. Here, we created a simple ribbon box plot with three categories (Category 1, Category 2, Category 3) along the x-axis and their corresponding distribution of values along the y-axis. We shade the ribbon boxes to indicate the intensity of the distribution within each category. Ribbon Box in Matplotlib In Matplotlib, a “ribbon box” is a visual representation used to display the distribution of a numeric variable across different categories or groups. While matplotlib does not have a specific function to create ribbon box plots, you can use other techniques available, such as − Use matplotlib”s plot() function to plot the central line for each category or group. This line represents the central tendency of the data within each category, such as the mean or median. Using the fill_between function to fill the area between two curves, where one curve represents the upper boundary of the ribbon and the other curve represents the lower boundary. Customize the appearance of the plot as needed by adding labels, titles, legends, gridlines, etc. Ribbon Box Plot with Confidence Interval In matplotlib, a simple ribbon box plot with confidence interval is a graphical representation used to display the central tendency of a dataset along with the uncertainty around that central value. It is like plotting the average of something (like daily temperatures) and shading an area around it to show how much the actual values might vary due to uncertainty. Example In the following example, we are creating a ribbon box plot showing the central tendency and confidence interval (uncertainity) around a sine wave, using matplotlib”s plot() and fill_between() functions, respectively − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y_mean = np.sin(x) # Standard deviation y_std = 0.1 # Plotting the central line plt.plot(x, y_mean, color=”blue”, label=”Mean”) # Plotting the shaded area representing the uncertainty (confidence interval) plt.fill_between(x, y_mean – y_std, y_mean + y_std, color=”blue”, alpha=0.2, label=”Uncertainty”) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Simple Ribbon Box Plot with Confidence Interval”) plt.legend() plt.grid(True) plt.show() Output Following is the output of the above code − Multiple Ribbon Box Plots In Matplotlib, multiple ribbon box plots are a way to compare the distributions of multiple datasets using ribbon box plots within the same plot. Each ribbon box plot represents the spread and central tendency of a different dataset, allowing for easy comparison between them. Example In here, we are generating multiple ribbon box plots with different colors to represent two sine and cosine waves along with their uncertainty bands using matplotlib − import matplotlib.pyplot as plt import numpy as np # Generating data x = np.linspace(0, 10, 100) y_means = [np.sin(x), np.cos(x)] # Standard deviations y_stds = [0.1, 0.15] colors = [”blue”, ”green”] # Plotting multiple ribbon box plots with different colors for y_mean, y_std, color in zip(y_means, y_stds, colors): plt.plot(x, y_mean, color=color, label=”Mean”, alpha=0.7) plt.fill_between(x, y_mean – y_std, y_mean + y_std, color=color, alpha=0.2) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Multiple Ribbon Box Plots with Different Colors”) plt.legend() plt.grid(True) plt.show() Output On executing the above code we will get the following output − Stacked Ribbon Box Plot In Matplotlib, stacked ribbon box plots are a type of graphical representation used to compare the distributions of multiple datasets while also showing the combined distribution of all the datasets. In a stacked ribbon box plot, each dataset is represented by its own ribbon box plot, just like in multiple ribbon box plots. However, instead of displaying the box plots side by side, they are stacked vertically on top of each other. This stacking allows for a direct comparison of the distributions of each dataset while also showing how they contribute to the overall distribution when combined. Example Now, we are plotting a stacked ribbon box plot, stacking the distributions of a sine and cosine wave to compare their variations across the x-axis using matplotlib − import matplotlib.pyplot as plt import numpy as np # Generating example data x = np.linspace(0, 10, 100) y1 = np.sin(x) y2 = np.cos(x) # Plotting stacked ribbon box plot plt.plot(x, y1, color=”blue”, label=”Dataset 1”) plt.fill_between(x, y1, color=”blue”, alpha=0.2) plt.plot(x, y2, color=”green”, label=”Dataset 2”) plt.fill_between(x, y2, color=”green”, alpha=0.2) plt.xlabel(”X”) plt.ylabel(”Y”) plt.title(”Stacked Ribbon Box Plot”) plt.legend() plt.grid(True) plt.show() Output After executing the above code, we get the following output − Horizontal Ribbon Box Plot A horizontal ribbon box plot in Matplotlib is a graphical representation that shows the distribution of a dataset along a horizontal axis using ribbon-shaped boxes. In a horizontal ribbon box plot, the dataset”s values are grouped into categories or bins, and for each category, a ribbon-shaped box is drawn horizontally. The length of each box represents the range of values within that category, while the position along the horizontal axis indicates the category itself. Example In the following example,
Matplotlib – Ellipse with Units ”; Previous Next An ellipse is a geometric shape that looks like a stretched circle. It is defined by two key properties: its major axis (the longest diameter) and its minor axis (the shortest diameter). These axes intersect at the center of the ellipse, and the shape of an ellipse is determined by the lengths of these axes. Both the distance from the center to the edge along the major axis and the distance from the center to the edge along the minor axis are important. In terms of units, you would measure these distances using some kind of unit, like inches, centimeters, or any other measurement you choose. So, when we say an ellipse with units, we mean that we are using specific measurements (units) to describe the size of the ellipse, considering both the length of the major axis and the length of the minor axis. Ellipse with Units in Matplotlib We can create an ellipse with units in Matplotlib using the “Ellipse” class in the “matplotlib.patches” module. The Ellipse class allows you to define the center, width and height (major and minor axes), angle of rotation, and other properties of the ellipse such as its rotation angle. The units of measurement for the axes depend on the coordinate system you are using. For example, if you are working with a plot in inches, the major and minor axes lengths would be in inches. Fixed Size Ellipse in Data Coordinates In Matplotlib, creating a fixed size ellipse in data coordinates involves drawing an ellipse on a plot with a specific size and position determined by data coordinates. This means that the dimensions of the ellipse are specified in the same units as your actual data. For instance, if you have a dataset with x and y values, you can draw an ellipse where the center is located at a particular (x, y) point, and the width and height of the ellipse are defined in terms of the data coordinates. Example we are drawing a simple ellipse with a fixed size specified in data coordinates. The center of the ellipse is located at (3, 5) on the plot, and the width is set to “4” units in meters, while the height is set to “2” units − import matplotlib.pyplot as plt from matplotlib.patches import Ellipse # Creating a plot fig, ax = plt.subplots() # Ellipse in data coordinates (units: meters) ellipse = Ellipse((3, 5), width=4, height=2, edgecolor=”b”, facecolor=”none”) ax.add_patch(ellipse) # Setting plot title and labels ax.set_title(”Fixed Size Ellipse in Data Coordinates”) ax.set_xlabel(”X-axis (meters)”) ax.set_ylabel(”Y-axis (meters)”) # Setting aspect ratio to ”equal” ax.set_aspect(”equal”) # Adjusting axis limits ax.set_xlim(0, 6) ax.set_ylim(3, 7) # Displaying dimensions plt.text(3, 5, f”Width: 4 metersnHeight: 2 meters”, ha=”center”, va=”center”, color=”red”, fontsize=10) plt.show() Output Following is the output of the above code − Ellipse with Variable Size in Axes Coordinates Creating an ellipse with variable size in axes coordinates in Matplotlib involves drawing an ellipse on a plot where the dimensions are specified in terms of the axes, rather than the actual data. In other words, the width and height of the ellipse are given as a percentage of the total length of the x and y axes, respectively. For example, if you want to visualize an ellipse that always covers 60% of the x-axis and 30% of the y-axis, regardless of the specific data values, you can use axes coordinates. This is particularly useful when you want the size of the ellipse to be relative to the overall dimensions of the plot. Example In here, we are drawing a an ellipse with a variable size specified in axes coordinates. The center of the ellipse is placed at (0.5, 0.5), which corresponds to the center of the plot. The width and height are set to 60% and 30% of the respective axis lengths, allowing the ellipse to scale with changes in the axes − import matplotlib.pyplot as plt from matplotlib.patches import Ellipse # Creating a plot fig, ax = plt.subplots() # Ellipse in axes coordinates ellipse = Ellipse((0.5, 0.5), width=0.6, height=0.3, edgecolor=”r”, facecolor=”none”, transform=ax.transAxes) ax.add_patch(ellipse) # Setting plot title and labels ax.set_title(”Ellipse with Variable Size in Axes Coordinates”) ax.set_xlabel(”X-axis (normalized)”) ax.set_ylabel(”Y-axis (normalized)”) # Displaying dimensions in the output plt.text(0.5, 0.5, f”Width: 0.6 (normalized)nHeight: 0.3 (normalized)”, ha=”center”, va=”center”, color=”blue”, fontsize=10, transform=ax.transAxes) plt.show() Output On executing the above code we will get the following output − Ellipse Centered at Figure Origin Creating an ellipse centered at figure origin in Matplotlib involves drawing an ellipse on a plot with its center positioned at the origin of the entire figure. The origin is the point (0, 0) in the coordinate system of the figure. In this case, the width and height of the ellipse are specified in the units of the figure, and the center of the ellipse is precisely at the origin. This demonstrates how to position an ellipse with respect to the overall figure rather than the individual axes. Example In the example below, we are creating an ellipse with its center at the origin of the figure (0, 0). The width is set to 4 units, and the height is set to 2 units − import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import numpy as np # Creating a plot fig, ax = plt.subplots() # Ellipse centered at figure origin ellipse = Ellipse((0, 0), width=4, height=2, edgecolor=”g”, facecolor=”none”, transform=ax.transData) ax.add_patch(ellipse) # Marking the center with a marker center_x, center_y = 0, 0 ax.plot(center_x, center_y, marker=”o”, markersize=8, color=”red”, label=”Center”) # Dotted line to represent the center ax.plot([center_x, center_x], [center_y, center_y], ”r–”) # Horizontal and vertical lines passing through the center ax.axhline(center_y, color=”blue”, linestyle=”–”, label=”Horizontal Line”) ax.axvline(center_x, color=”purple”,
Matplotlib – Click Events
Matplotlib – Click Events ”; Previous Next In general, a click event occurs when a user interacts with a computer interface by pressing and releasing a mouse button or tapping on a touchscreen device. This event serves as a trigger for the computer system to recognize and respond to the user”s input. In the context of data visualization, like in Matplotlib or other plotting libraries, a click event can be used to capture specific user interactions with the plot, offering a dynamic and interactive experience. This could include tasks such as selecting data points, triggering updates or enabling user-initiated actions. Click Events in Matplotlib In Matplotlib, a click event occurs when a user interacts with a plot by clicking on the figure or a specific region within it. These events are associated with callback functions that are executed when the click happens. This can be done by connecting a callback function to the button_press_event using the mpl_connect() method on the figure canvas. Let”s see a basic example that demonstrates how a simple click event works. Example In this example, a click event is handled by the onclick function, which prints a message to the console when the user clicks anywhere on the plot. The figure contains a text element prompting the user to click. import numpy as np import matplotlib.pyplot as plt def onclick(event): print(”The Click Event Triggered!”) fig, ax = plt.subplots(figsize=(7, 4)) ax.text(0.1, 0.5, ”Click me anywhere on this plot!”, dict(size=20)) cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! The Click Event Triggered! Watch the video below to observe how the click event feature works here. Storing Click Event Coordinates Storing click event coordinates allows you to gather information about user interactions on a plot, facilitating tasks such as data point selection or analysis. Example Here is an example that stores and prints the coordinates of mouse clicks on the plot. This demonstrates how click events can be used to gather information about user interactions on a plot. import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 2*np.pi, 0.01) y = np.sin(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) clicked_coords = [] def onclick(event): global ix, iy ix, iy = event.xdata, event.ydata print(f”Clicked at x = {ix}, y = {iy}”) global clicked_coords clicked_coords.append((ix, iy)) # Disconnect the click event after collecting 5 coordinates if len(clicked_coords) == 5: fig.canvas.mpl_disconnect(cid) print(”Reached the maximum clicks…”) cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − Clicked at x = 0.0743760368663593, y = 0.11428680137603275 Clicked at x = 1.4368755760368663, y = 0.9928568371128363 Clicked at x = 3.130449769585254, y = 0.10714395555703438 Clicked at x = 4.7221548387096774, y = -1.014282838025715 Clicked at x = 6.377528110599078, y = 0.04285834318604875 Reached the maximum clicks… Watch the video below to observe how the click event feature works here. Click Event with Checkbox Integrating the checkbox widget with click events offers a dynamic way to control user interactions on the plots. By combining checkboxes with click events, you can enable or disable certain features, providing users with interactive control over the plot. Example In this example, a checkbox is used to control the adding text on the plot where the click event is triggered. import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons import numpy as np def onclick(event): # Only use events within the axes. if not event.inaxes == ax1: return # Check if Checkbox is “on” if check_box.get_status()[0]: ix, iy = event.xdata, event.ydata coords3.append((ix, iy)) # write text with coordinats where clicks occur if len(coords3) >= 1: ax1.annotate(f”* {ix:.1f}, {iy:.1f}”, xy=(ix, iy), color=”green”) fig.canvas.draw_idle() # Disconnect after 6 clicks if len(coords3) >= 6: fig.canvas.mpl_disconnect(cid) print(”Reached the maximum clicks…”) plt.close(fig) x = np.arange(0, 2*np.pi, 0.01) y = np.sin(2*x) fig, ax1 = plt.subplots(figsize=(7, 4)) ax1.plot(x, y) ax1.set_title(”This is my plot”) ax2 = plt.axes([0.7, 0.05, 0.1, 0.075]) check_box = CheckButtons(ax2, [”On”,], [False,], check_props={”color”:”red”, ”linewidth”:1}) coords3 = [] cid = fig.canvas.mpl_connect(”button_press_event”, onclick) plt.show() Output On executing the above code we will get the following output − Reached the maximum clicks… Watch the video below to observe how the click event feature works here. Print Page Previous Next Advertisements ”;
Matplotlib – Histogram
Matplotlib – Histogram ”; Previous Next A histogram is like a visual summary that shows how often different values appear in a set of data. Imagine you have a collection of numbers, like ages of people. A histogram divides these numbers into groups, called “bins,” and then uses bars to represent how many numbers fall into each bin. The taller the bar, the more numbers are in that group. Histogram in Matplotlib We can create a histogram in Matplotlib using the hist() function. This function allows us to customize various aspects of the histogram, such as the number of bins, color, and transparency. Histogram in Matplotlib is used to represent the distribution of numerical data, helping you to identify patterns. The hist() Function The hist() function in Matplotlib takes a dataset as input and divides it into intervals (bins). It then displays the frequency (count) of data points falling within each bin as a bar graph. Following is the syntax of hist() function in Matplotlib − Syntax plt.hist(x, bins=None, range=None, density=False, cumulative=False, color=None, edgecolor=None, …) Where, x is the input data for which the histogram is determined. bins (optional) is the number of bins or the bin edges. range (optional) is the lower and upper range of the bins. Default is the minimum and maximum of x If density (optional) is True, the histogram represents a probability density function. Default is False. If cumulative (optional) is True, a cumulative histogram is computed. Default is False. These are just a few parameters; there are more optionals parameters available for customization. Creating a Vertical Histogram In Matplotlib, creating a vertical histogram involves plotting a graphical representation of the frequency distribution of a dataset, with the bars oriented vertically along the y-axis. Each bar represents the frequency or count of data points falling within a particular interval or bin along the x-axis. Example In the following example, we are creating a vertical histogram by setting the “orientation” parameter to “vertical” within the hist() function − import matplotlib.pyplot as plt plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True x = [1, 2, 3, 1, 2, 3, 4, 1, 3, 4, 5] plt.hist(x, orientation=”vertical”) plt.show() Output We get the output as shown below − Customized Histogram with Density When we create a histogram with density, we are providing a visual summary of how data is distributed. We use this graph to see how likely different numbers are occurring, and the density option makes sure the total area under the histogram is normalized to one. Example In the following example, we are visualizing random data as a histogram with 30 bins, displaying it in green with a black edge. We are using the density=True parameter to represent the probability density − import matplotlib.pyplot as plt import numpy as np # Generate random data data = np.random.randn(1000) # Create a histogram with density and custom color plt.hist(data, bins=30, density=True, color=”green”, edgecolor=”black”, alpha=0.7) plt.xlabel(”Values”) plt.ylabel(”Probability Density”) plt.title(”Customized Histogram with Density”) plt.show() Output After executing the above code, we get the following output − Cumulative Histogram When we create a cumulative histogram, we graphically represent the total number of occurrences of values up to a certain point. It shows how many data points fall below or equal to a certain value. Example In here, we are using a histogram where each bar represents a range of exam scores, and the height of the bar tells us how many students, in total, scored within that range. By setting the cumulative=True parameter in the hist() function, we make sure that the histogram shows the cumulative progression of scores − import matplotlib.pyplot as plt import numpy as np # Generate random exam scores (out of 100) exam_scores = np.random.randint(0, 100, 150) # Create a cumulative histogram plt.hist(exam_scores, bins=20, cumulative=True, color=”orange”, edgecolor=”black”, alpha=0.7) plt.xlabel(”Exam Scores”) plt.ylabel(”Cumulative Number of Students”) plt.title(”Cumulative Histogram of Exam Scores”) plt.show() Output Following is the output of the above code − Histogram with Different Color and Edge Color When creating a histogram, we can customize the fill color and edge color, adding a visual touch to represent the data distribution. By doing this, we blend the histogram with a stylish and distinctive appearance. Example Now, we are generating a histogram for random data with 25 bins, and we are presenting it in purple color with blue edges − import matplotlib.pyplot as plt import numpy as np data = np.random.randn(1000) # Creating a histogram with different color and edge color plt.hist(data, bins=25, color=”purple”, edgecolor=”blue”) plt.xlabel(”Values”) plt.ylabel(”Frequency”) plt.title(”Histogram with Different Color and Edge Color”) plt.show() Output On executing the above code we will get the following output − Example To plot a histogram with colors, we can also extract colors from the “cm” parameter in the setp() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams[“figure.figsize”] = [7.00, 3.50] plt.rcParams[“figure.autolayout”] = True data = np.random.random(1000) n, bins, patches = plt.hist(data, bins=25, density=True, color=”red”, rwidth=0.75) col = (n-n.min())/(n.max()-n.min()) cm = plt.cm.get_cmap(”RdYlBu”) for c, p in zip(col, patches): plt.setp(p, ”facecolor”, cm(c)) plt.show() Output On executing the above code we will get the following output − Example In here, we are specifying different colors for different bars in a matplotlib histogram by iterating in the range of number of bins and setting random facecolor for each bar − import numpy as np import matplotlib.pyplot as plt import random import string # Set the figure size plt.rcParams[“figure.figsize”] = [7.50, 3.50] plt.rcParams[“figure.autolayout”] = True # Figure and set of subplots fig, ax = plt.subplots() # Random data data = np.random.rand(100) # Plot
Matplotlib – Pie Chart
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 ”;
Matplotlib – Scatter Plot
Matplotlib – Scatter Plot ”; Previous Next Scatter plots are used to plot data points on horizontal and vertical axis in the attempt to show how much one variable is affected by another. Each row in the data table is represented by a marker the position depends on its values in the columns set on the X and Y axes. A third variable can be set to correspond to the color or size of the markers, thus adding yet another dimension to the plot. The script below plots a scatter diagram of grades range vs grades of boys and girls in two different colors. import matplotlib.pyplot as plt girls_grades = [89, 90, 70, 89, 100, 80, 90, 100, 80, 34] boys_grades = [30, 29, 49, 48, 100, 48, 38, 45, 20, 30] grades_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] fig=plt.figure() ax=fig.add_axes([0,0,1,1]) ax.scatter(grades_range, girls_grades, color=”r”) ax.scatter(grades_range, boys_grades, color=”b”) ax.set_xlabel(”Grades Range”) ax.set_ylabel(”Grades Scored”) ax.set_title(”scatter plot”) plt.show() Print Page Previous Next Advertisements ”;
Matplotlib – Reverse Axes
Matplotlib – Reverse Axes ”; Previous Next What is Reverse Axes? In Matplotlib reverse axes refers to changing the direction of an axis, flipping it from its default orientation. This action alters the visual representation of the plot by reversing the order of the data along a specific axis usually the x-axis or y-axis. Reversing X-axis To reverse the x-axis in Matplotlib we can use the plt.gca().invert_xaxis() function. This method inverts the direction of the x-axis effectively flipping the plot horizontally. Data points that were originally plotted from left to right will now be displayed from right to left. Here is a detailed breakdown of how to reverse the x-axis: Steps to Reverse the X-axis The below are the steps to be followed to reverse the x-axis. Create a Plot Generate a plot with our data using Matplotlib. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plot with default axis orientation plt.plot(x, y, marker=”o”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Default X-axis”) plt.show() Output Reverse the X-axis After creating the plot use plt.gca().invert_xaxis() to reverse the x-axis. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plot with default axis orientation plt.plot(x, y, marker=”o”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Default X-axis”) plt.show() # Reversing the x-axis plt.plot(x, y, marker=”o”) plt.gca().invert_xaxis() # Reverse x-axis plt.xlabel(”Reversed X-axis”) plt.ylabel(”Y-axis”) plt.title(”Reversed X-axis”) plt.show() Output The second plot will display the same data as the first one but the x-axis will be reversed. Data points that were initially on the left side will now appear on the right side by altering the visual representation of the data. Use Cases for Reversing the X-axis Flipping Time Series Data − When we are plotting time series data then reversing the x-axis might better align with the chronological order. Reorienting Geographical Plots − In some geographical plots reversing the x-axis could match the expected orientation or conventions. Reversing the x-axis provides an alternative perspective for visualizing data allowing us to present information in a different order or orientation for clearer insights or better alignment with conventions. This function reverses the direction of the x-axis by flipping the plot horizontally. Data points that were originally plotted from left to right will now be displayed from right to left. Reversing Y-axis The plt.gca().invert_yaxis() function reverses the direction of the y-axis by flipping the plot vertically. Data points that were originally plotted from bottom to top will now be displayed from top to bottom. The reversing of Y – axis is also as same as the reversing the X – axis of a plot which we seen in the upper section. The below are the steps to be followed for reversing the Y – axis. Create a Plot Generate a plot with our data using Matplotlib. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plot with default axis orientation plt.plot(x, y, marker=”o”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Default Y-axis”) plt.show() Output Reverse the Y-axis After creating the plot use plt.gca().invert_yaxis() to reverse the y-axis. Example import matplotlib.pyplot as plt # Sample data x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # Plot with default axis orientation plt.plot(x, y, marker=”o”) plt.xlabel(”X-axis”) plt.ylabel(”Y-axis”) plt.title(”Default Y-axis”) plt.show() # Reversing the x-axis # Reversing the y-axis plt.plot(x, y, marker=”o”) plt.gca().invert_yaxis() # Reverse y-axis plt.xlabel(”X-axis”) plt.ylabel(”Reversed Y-axis”) plt.title(”Reversed Y-axis”) plt.show() Output Print Page Previous Next Advertisements ”;
Matplotlib – Subplots() Function ”; Previous Next Matplotlib’spyplot API has a convenience function called subplots() which acts as a utility wrapper and helps in creating common layouts of subplots, including the enclosing figure object, in a single call. Plt.subplots(nrows, ncols) The two integer arguments to this function specify the number of rows and columns of the subplot grid. The function returns a figure object and a tuple containing axes objects equal to nrows*ncols. Each axes object is accessible by its index. Here we create a subplot of 2 rows by 2 columns and display 4 different plots in each subplot. import matplotlib.pyplot as plt fig,a = plt.subplots(2,2) import numpy as np x = np.arange(1,5) a[0][0].plot(x,x*x) a[0][0].set_title(”square”) a[0][1].plot(x,np.sqrt(x)) a[0][1].set_title(”square root”) a[1][0].plot(x,np.exp(x)) a[1][0].set_title(”exp”) a[1][1].plot(x,np.log10(x)) a[1][1].set_title(”log”) plt.show() The above line of code generates the following output − Print Page Previous Next Advertisements ”;