Python matplotlib log scale

Matplotlib Log Scale Using Various Methods in Python

Matplotlib Log Scale

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()

y-axis to Matplotlib log scale

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()

Semilogx() or Semilogy() functions

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))

logscale Histogram Plot

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()

matplotlib logscale Histogram Plot

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 –

  1. 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.
  2. 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!

Источник

Как создавать графики Matplotlib с логарифмическими шкалами

Как создавать графики Matplotlib с логарифмическими шкалами

Часто вам может понадобиться создать графики Matplotlib с логарифмическими шкалами для одной или нескольких осей. К счастью, Matplotlib предлагает для этого следующие три функции:

  • Matplotlib.pyplot.semilogx() — построить график с логарифмическим масштабированием по оси X.
  • Matplotlib.pyplot.semilogy () — построить график с логарифмическим масштабированием по оси Y.
  • Matplotlib.pyplot.loglog() — построить график с логарифмическим масштабированием по обеим осям.

В этом руководстве объясняется, как использовать каждую из этих функций на практике.

Пример 1: Логарифмическая шкала для оси X

Предположим, мы создаем линейную диаграмму для следующих данных:

import matplotlib.pyplot as plt #create data x = [1, 8, 190, 1400, 6500] y = [1, 2, 3, 4, 5] #create line chart of data plt.plot (x,y) 

Мы можем использовать функцию .semilogx() для преобразования оси x в логарифмическую шкалу:

График Matplotlib с логарифмической шкалой по оси X

Обратите внимание, что ось Y точно такая же, но ось X теперь имеет логарифмическую шкалу.

Пример 2: Логарифмическая шкала для оси Y

Предположим, мы создаем линейную диаграмму для следующих данных:

import matplotlib.pyplot as plt #create data x = [1, 2, 3, 4, 5] y = [1, 8, 190, 1400, 6500] #create line chart of data plt.plot (x,y) 

Мы можем использовать функцию .semilogy() для преобразования оси Y в логарифмическую шкалу:

Matplotlib с логарифмической шкалой по оси Y

Обратите внимание, что ось X точно такая же, но ось Y теперь имеет логарифмическую шкалу.

Пример 3: Логарифмическая шкала для обеих осей

Предположим, мы создаем линейную диаграмму для следующих данных:

import matplotlib.pyplot as plt #create data x = [10, 200, 3000, 40000, 500000] y = [30, 400, 5000, 60000, 750000] #create line chart of data plt.plot (x,y) 

Мы можем использовать функцию .loglog() для преобразования оси Y в логарифмическую шкалу:

График журнала журнала в Matplotlib

Обратите внимание, что обе оси теперь имеют логарифмическую шкалу.

Источник

Оцените статью