
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Logarithmic Bins in a Python Histogram
In Python to create a logarithmic bin, we can use Numpy library to generate logarithmically spaced bins, and using matplotlib for creating a histogram.
Logarithmic bins in a Python histogram refer to bins that are spaced logarithmically rather than linearly. We can set the logarithmic bins while plotting histograms by using plt.hist(bin="")
Steps to Create Logarithmic Bins
To set logarithmic bins in a Python histogram, the steps are as follows.
-
Import Libraries: Importing 'matplotlib' for plotting and 'numpy' for performing numerical computations.
-
Creating the Data Array: Creating a NumPy array containing integers, to represent the data.
-
Plotting the Histogram: By using 'plt.hist()' function plotting an histogram with key parameters as 'x' and 'bins'
-
Setting the X-axis to a logarithmic Scale: The plt.gca()('get current axes') returns the current Axes instance on the plot
-
Display the Plot: Displaying the plot in a window by using 'plt.show()
Import Libraries
importing matplotlib.pyplot is a collection of functions used to create various types of plots and numpy library for working with arrays and handling numerical computations.
from matplotlib import pyplot as plt import numpy as np
Creating the Data Array
In the below code line np.array(range(100)) refers to creating a NumPy array containing integers from 0 to 99.
x = np.array(range(100))
Plotting Histogram
Using the code below Key arguments 'x' and 'bins' are used by the plt.hist() method to build the histogram. Numbers spaced on a log scale will be generated using np,logspace(). stop=np, start=np.log10(10).The beginning and ending points of the bins in the logarithm are denoted by log10(15).
plt.hist(x, bins=np.logspace(start=np.log10(10) stop=np.log10(15), num=10))
Setting the X-axis to a logarithm scale
The plt.gca() stands for 'get current axes' which returns the current Axes instance on the plot and set_xscale("log") will change the x-axis to a logarithmic scale to display the values in alog scale.
plt.gca().set_xscale("log")
Displaying the Plot
To display the plot in a window or inline 'plt.show()' function is used.
plt.show()
Example
From matplotlib import pyplot as plt import numpy as np x = np.array(range(100))plt.hist(x, bins=np.logspace(start=np.log10(10), stop=np.log10(15), num=10)) plt.gca().set_xscale("log") plt.show()