- Matplotlib Logarithmic Scale
- Introduction
- What are Logarithms in Matplotlib?
- When Would You Use a Logarithmic Scale?
- Syntax of Logarithmic Scale in Matplotlib in Different Interface
- Logarithmic Scale on Pyplot Interface
- Logarithmic Scale on Object-Oriented Interface in Matplotlib
- How to Plot Logarithmic Axes in Matplotlib?
- Examples
- Conclusion
- Matplotlib Log Scale Using Various Methods in Python
- Changing y-axis to Matplotlib log scale
- Explanation:
- Matplotlib Log Scale Using Semilogx() or Semilogy() functions
- Explanation:
- Matplotlib Log Scale Using loglog() function
- Explanation:
- Scatter plot with Matplotlib log scale in Python
- Explanation:
- Matplotlib logscale Histogram Plot
- Explanation:
- How to Plot Negative Values on Matplotlib Logscale?
- Conclusion:
Matplotlib Logarithmic Scale
Matplotlib provides the modules and function to add a logarithmic scale on a figure, and there are two ways to do it. The first method is set_xscale() and set_yscale() . These functions are used when we are in an object-oriented interface. The second method is x_scale() and y_scale() . These functions are used when we are in the pyplot interface. The logarithmic scale is a non-linear scale that shows very large or small values on the graph. It has various applications in fields like geology, forensic science, mathematics, etc.
Introduction
Before going to the logarithmic scale, we must first understand what we mean by logarithm. Log is an alternative way of representing exponential quantities, for example, 2 1 0 = 1 0 2 4 2^ = 1024 2 1 0 = 1 0 2 4 , which can also be expressed as l o g 2 ( 1 0 2 4 ) = 1 0 log = 10 l o g 2 ( 1 0 2 4 ) = 1 0 .
The logarithm scale is a non-linear scale that analyzes an extensive range of values. Instead of equal increments, each interval is increased by a factor of the base of the logarithm. On a linear scale, integers are represented on the axes, increasing as we move ahead. If we plot coordinates with some value like 1 , 2 , or maybe 100 , that can be easily represented on a linear scale. What about if we plot the population of all countries on a graph or may be dealing with some exponential equation? In that case, a linear scale would be impractical. Instead, we have to use a logarithmic scale in which one axis represents a consistent integer increment and another, the logarithmic scale, represents an increment in the power of 10 .
What are Logarithms in Matplotlib?
Logarithms in matplotlib are used to scale the axes according to the given data. When we plot large or small numbers without scaling the axes, data may squeeze too closely or not be covered in a graph. For visualization of these types of data, we use logarithmic scale in matplotlib to scale the axes according to the data.
When Would You Use a Logarithmic Scale?
The logarithmic scale is used when we plot large values on a graph. Such data cannot be plotted on a plane having axes of equal increment (linear scale).
A logarithmic scale in which one axis has the value in a regular interval, and the other axis has values incrementing at the power of 10 is used to plot larger values in mathematics.
When we deal with the exponential function, we use the logarithmic scale, also in forensic science when we study exponential decay, and in geology to measure the seismic activity of earthquakes on the Richter scale.
Syntax of Logarithmic Scale in Matplotlib in Different Interface
Logarithmic Scale on Pyplot Interface
In the pyplot interface, we can use the functions xscale() and yscale() to add a logarithmic scale on the axes. But, first, we will discuss the syntax and parameters of these functions.
Syntax of xscale() method
xscale() method is used to scale the x-axis like linear, log, symlog, logit, etc
- Value: it is used to set the scale linear,log,symlog,logit, . >
- kwargs: Different keyword arguments are accepted, depending on the scale ( matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale )
Syntax of yscale method
yscale() method is used to scale the y-axis like linear, log, symlog, logit, etc
- Value: it is used to set the scale linear,log,symlog,logit, . >
- kwargs: Different keyword arguments are accepted, depending on the scale ( matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale )
Logarithmic Scale on Object-Oriented Interface in Matplotlib
If we use the object-oriented interface in matplotlib, like for plotting the data, we create a figure and then add subplots to it, then we should use the functions set_xscale() and set_yscale() to change the scale of the axes to logarithmic. We will discuss the syntax and parameters of these parameters.
Syntax of set_xscale() method matplotlib.axes.Axes.set_xscale(value, **kwargs)
- Value: it is used to set the scale linear,log,symlog,logit, . >
- kwargs: Different keyword arguments are accepted, depending on the scale ( matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale )
Syntax of set_yscale() method matplotlib.axes.Axes.set_yscale(value, **kwargs)
- value: it is used to set the scale linear,log,symlog,logit, . >
- kwargs: Different keyword arguments are accepted, depending on the scale ( matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale )
How to Plot Logarithmic Axes in Matplotlib?
In the pyplot interface, by using the functions xscale() and yscale() , we can change the scale of the X and Y axis to logarithmic.
Example: Logarithmic axes in matplotlib
Output:
Examples
Example 1: Setting log scale on x-axis
In this example, we will understand how we can change the scale of the axis from scaler to linear on the x-axis.
Output:
Example 2: Setting log scale on the y-axis
In this example, we will understand how we can change the scale of the axis from scaler to linear on the y-axis.
Output:
Example 3: Bar graph on logarithmic scale
This example will explain implementing a bar graph on a logarithmic scale.
Output:
Example 4: Changing the base of the logarithmic scale
When dealing with the logarithms, setting the ticks to the base 10 is not important. However, for accuracy and a better understanding of the plot, we can change the base of the logarithm. Below is how we can change the base of the logarithmic scale.
Output:
Conclusion
- Logarithmic scale efficiently visualizes a graph’s very large or small values.
- Logarithmic scale is non-linear.
- It is used to visualize the exponential function on a graph.
- xscale() and yscale() are the methods for changing the scaling of the axes in matplotlib.
Matplotlib Log Scale Using Various Methods in Python
Hello programmers, in today’s article, we will learn about the Matplotlib Logscale in Python. Matplotlib log scale is a scale having powers of 10. You could use any base, like 2, or the natural logarithm value is given by the number e. Using different bases would narrow or widen the spacing of the plotted elements, making visibility easier. We can use the Matlplotlib log scale for plotting axes, histograms, 3D plots, etc. Let’s take a look at different examples and implementations of the log scale.
Logarithmic Scales are a very important data visualization technique. This scale allows us to witness the exponential growth of a system on a linear scale. For example, the cases of Novel Corona Virus are increasing in an exponential manner, In such cases, using log scales helps you to check the control of the virus.
Changing y-axis to Matplotlib log scale
from matplotlib import pyplot # Create a subplot to show the graph pyplot.subplot(1, 1, 1) # Powers of 10 a = [10**i for i in range(10)] # Plotting the graph pyplot.plot(a, color='blue', lw=2) # Setting a logarithmic scale for y-axis pyplot.yscale('log') pyplot.show()
Explanation:
The process of plot logarithmic axes is similar to regular plotting, except for one line of code specifying the type of axes as ‘log.’ In the above example, we first set up the subplot required plot the graph. We will then plot the powers of 10 against their exponents. This is a linear, logarithmic graph. Without the logarithmic scale, the data plotted would show a curve with an exponential rise. Thus to obtain the y-axis in log scale, we will have to pass ‘log’ as an argument to the pyplot.yscale(). Similarly, you can apply the same to change the x-axis to log scale by using pyplot.xscale(‘log’)
Matplotlib Log Scale Using Semilogx() or Semilogy() functions
import pandas as pd import matplotlib.pyplot as plt x = [10, 100, 1000, 10000, 100000] y = [2, 4 ,8, 16, 32] fig = plt.figure(figsize=(8, 6)) plt.scatter(x,y) plt.plot(x,y) plt.grid() plt.semilogx() plt.semilogy(basey=2) plt.xlabel("x",fontsize=20) plt.ylabel("y",fontsize=20) plt.show()
Explanation:
The semilogx() function is another method of creating a plot with log scaling along the X-axis. While the semilogy() function creates a plot with log scaling along Y-axis. The default base of the logarithm is 10. We can, however, set the base with basex and basey parameters for the function semilogx() and semilogy(), respectively. In the above example, the plt.semilogx() function with default base 10 is used to change the x-axis to a logarithmic scale. While the plt.semilogy() function changes the y-axis to base 2 log scale.
Matplotlib Log Scale Using loglog() function
import pandas as pd import matplotlib.pyplot as plt x = [10, 100, 1000, 10000, 100000] y = [2, 4 ,8, 16, 32] fig = plt.figure(figsize=(8, 6)) plt.scatter(x,y) plt.plot(x,y) plt.loglog(basex=10,basey=2) plt.show()
Explanation:
We can also implement log scaling along both X and Y axes by using the loglog() function. The base of the logarithm for the X-axis and Y-axis is set by basex and basey parameters. In the above example, basex = 10 and basey = 2 is passed as arguments to the plt.loglog() function which returns the base 10 log scaling x-axis. And base 2 log scaling along the y-axis.
Scatter plot with Matplotlib log scale in Python
import matplotlib.pyplot as plt import numpy as np f, ax = plt.subplots() ax.set_xscale('log') ax.set_yscale('log') ax.scatter(2**np.arange(10), 2**np.arange(10))
Explanation:
In the above example, the axes are the first log scaled, bypassing ‘log’ as a parameter to the ser_xscale() and set_yscale() functions. The plt.scatter() function is then called, which returns the scatter plot on a logarithmic scale. The margins of the plot are huge. However, if the plt.scatter() method is used before log scaling the axes, the scatter plot appears normal.
Matplotlib logscale Histogram Plot
histogram on linear scale plt.subplot(211) hist, bins, _ = plt.hist(x, bins=8) # histogram on log scale. # Use non-equal bin sizes, such that they look equal on log scale. logbins = np.logspace(np.log10(bins[0]),np.log10(bins[-1]),len(bins)) plt.subplot(212) plt.hist(x, bins=logbins) plt.xscale('log') plt.show()
Explanation:
In the above example, the Histogram plot is once made on a normal scale. And also plotted on Matplotlib log scale. For plotting histogram on a logarithmic scale, the bins are defined as ‘logbins.’ Also, we use non-equal bin sizes, such that they look equal on a log scale. The x-axis is log scaled, bypassing ‘log’ as an argument to the plt.xscale() function.
How to Plot Negative Values on Matplotlib Logscale?
Sometimes, your data contains both positive and negative values. In such scenarios, the log scale won’t work since log values of negative numbers doesnt exists. In such cases, we have couple of options to follow –
- Shift the origin to the lowest value of the dataset. This means the lowest value in your dataset will become 0 and every other value will be increased by the absolute of your lowest value. arr = arr + min(arr) will give you the non negative values.
- Using Symmetric Log Scale. This scale will value both sides of 0. Use plt.yscale(‘symlog’) to apply a symmetric log scale on the yaxis.
Conclusion:
In this article, we have discussed various ways of changing into a logarithmic scale using the Matplotlib logscale in Python. We have seen different functions to implement log scaling to axes. Like semilogx() or semilogy() functions and loglog() functions. We also cited examples of using Matplotlib logscale to plot to scatter plots and histograms. Refer to this article in case of any queries regarding the use of Matplotlib Logscale.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Happy Pythoning!