标签归档:logarithm

在Python中如何用numpy处理自然日志(例如“ ln()”)?

问题:在Python中如何用numpy处理自然日志(例如“ ln()”)?

使用numpy,如何执行以下操作:

ln(x)

它等效于:

np.log(x)

我这样一个看似微不足道的问题道歉,但我之间的差异的理解logln被认为ln是LOGSPACEè?

Using numpy, how can I do the following:

ln(x)

Is it equivalent to:

np.log(x)

I apologise for such a seemingly trivial question, but my understanding of the difference between log and ln is that ln is logspace e?


回答 0


回答 1

正确,np.log(x)是的自然日志(基本e日志)x

对于其他基准,请记住该日志定律:log-b(x) = log-k(x) / log-k(b)log-b任意任意基准中b,log是哪里,log-k在基准中是log k,例如

这里k = e

l = np.log(x) / np.log(100)

并且l是x的log-base-100

Correct, np.log(x) is the Natural Log (base e log) of x.

For other bases, remember this law of logs: log-b(x) = log-k(x) / log-k(b) where log-b is the log in some arbitrary base b, and log-k is the log in base k, e.g.

here k = e

l = np.log(x) / np.log(100)

and l is the log-base-100 of x


回答 2

我通常这样做:

from numpy import log as ln

也许这可以使您更舒适。

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.


回答 3

您可以简单地通过将日志的底数设为e来进行相反的操作。

import math

e = 2.718281

math.log(e, 10) = 2.302585093
ln(10) = 2.30258093

You could simple just do the reverse by making the base of log to e.

import math

e = 2.718281

math.log(e, 10) = 2.302585093
ln(10) = 2.30258093

回答 4

from numpy.lib.scimath import logn
from math import e

#using: x - var
logn(e, x)
from numpy.lib.scimath import logn
from math import e

#using: x - var
logn(e, x)

登录到以2为底的python

问题:登录到以2为底的python

我应该如何计算以python为底数的两个日志。例如。我在使用对数基数2的地方有这个方程式

import math
e = -(t/T)* math.log((t/T)[, 2])

How should I compute log to the base two in python. Eg. I have this equation where I am using log base 2

import math
e = -(t/T)* math.log((t/T)[, 2])

回答 0

很高兴知道

但也知道它 math.log带有一个可选的第二个参数,该参数允许您指定基数:

In [22]: import math

In [23]: math.log?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:    <built-in function log>
Namespace:  Interactive
Docstring:
    log(x[, base]) -> the logarithm of x to the given base.
    If the base not specified, returns the natural logarithm (base e) of x.


In [25]: math.log(8,2)
Out[25]: 3.0

It’s good to know that

but also know that math.log takes an optional second argument which allows you to specify the base:

In [22]: import math

In [23]: math.log?
Type:       builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:    <built-in function log>
Namespace:  Interactive
Docstring:
    log(x[, base]) -> the logarithm of x to the given base.
    If the base not specified, returns the natural logarithm (base e) of x.


In [25]: math.log(8,2)
Out[25]: 3.0

回答 1

浮动→浮动 math.log2(x)

import math

log2 = math.log(x, 2.0)
log2 = math.log2(x)   # python 3.4 or later

浮点数→整数 math.frexp(x)

如果您只需要浮点数的对数2的整数部分,则提取指数非常有效:

log2int_slow = int(math.floor(math.log(x, 2.0)))
log2int_fast = math.frexp(x)[1] - 1
  • Python frexp()调用C函数frexp(),该函数仅捕获和调整指数。

  • Python frexp()返回一个元组(尾数,指数)。因此[1]得到指数部分。

  • 对于2的整数次方,指数比您期望的多一。例如,将32存储为0.5×2⁶。- 1上面解释了这一点。也适用于1/32(存储为0.5×2⁻⁴)。

  • 朝向负无穷大,因此log 2 31是4而不是5。log 2(1/17)是-5不是-4。


整数→整数 x.bit_length()

如果输入和输出均为整数,则此本机整数方法可能非常有效:

log2int_faster = x.bit_length() - 1
  • - 1因为2ⁿ需要n + 1位。适用于非常大的整数,例如2**10000

  • 朝向负无穷大,因此log 2 31是4而不是5。log 2(1/17)是-5不是-4。

float → float math.log2(x)

import math

log2 = math.log(x, 2.0)
log2 = math.log2(x)   # python 3.3 or later

float → int math.frexp(x)

If all you need is the integer part of log base 2 of a floating point number, extracting the exponent is pretty efficient:

log2int_slow = int(math.floor(math.log(x, 2.0)))
log2int_fast = math.frexp(x)[1] - 1
  • Python frexp() calls the C function frexp() which just grabs and tweaks the exponent.

  • Python frexp() returns a tuple (mantissa, exponent). So [1] gets the exponent part.

  • For integral powers of 2 the exponent is one more than you might expect. For example 32 is stored as 0.5×2⁶. This explains the - 1 above. Also works for 1/32 which is stored as 0.5×2⁻⁴.

  • Floors toward negative infinity, so log₂31 computed this way is 4 not 5. log₂(1/17) is -5 not -4.


int → int x.bit_length()

If both input and output are integers, this native integer method could be very efficient:

log2int_faster = x.bit_length() - 1
  • - 1 because 2ⁿ requires n+1 bits. Works for very large integers, e.g. 2**10000.

  • Floors toward negative infinity, so log₂31 computed this way is 4 not 5.


回答 2

如果您使用的是python 3.4或更高版本,则它已经具有用于计算log2(x)的内置函数

import math
'finds log base2 of x'
answer = math.log2(x)

如果您使用的是旧版本的python,则可以这样做

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math
'finds log base2 of x'
answer = math.log2(x)

If you are on older version of python then you can do like this

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

回答 3

使用numpy:

In [1]: import numpy as np

In [2]: np.log2?
Type:           function
Base Class:     <type 'function'>
String Form:    <function log2 at 0x03049030>
Namespace:      Interactive
File:           c:\python26\lib\site-packages\numpy\lib\ufunclike.py
Definition:     np.log2(x, y=None)
Docstring:
    Return the base 2 logarithm of the input array, element-wise.

Parameters
----------
x : array_like
  Input array.
y : array_like
  Optional output array with the same shape as `x`.

Returns
-------
y : ndarray
  The logarithm to the base 2 of `x` element-wise.
  NaNs are returned where `x` is negative.

See Also
--------
log, log1p, log10

Examples
--------
>>> np.log2([-1, 2, 4])
array([ NaN,   1.,   2.])

In [3]: np.log2(8)
Out[3]: 3.0

Using numpy:

In [1]: import numpy as np

In [2]: np.log2?
Type:           function
Base Class:     <type 'function'>
String Form:    <function log2 at 0x03049030>
Namespace:      Interactive
File:           c:\python26\lib\site-packages\numpy\lib\ufunclike.py
Definition:     np.log2(x, y=None)
Docstring:
    Return the base 2 logarithm of the input array, element-wise.

Parameters
----------
x : array_like
  Input array.
y : array_like
  Optional output array with the same shape as `x`.

Returns
-------
y : ndarray
  The logarithm to the base 2 of `x` element-wise.
  NaNs are returned where `x` is negative.

See Also
--------
log, log1p, log10

Examples
--------
>>> np.log2([-1, 2, 4])
array([ NaN,   1.,   2.])

In [3]: np.log2(8)
Out[3]: 3.0

回答 4

http://en.wikipedia.org/wiki/Binary_logarithm

def lg(x, tol=1e-13):
  res = 0.0

  # Integer part
  while x<1:
    res -= 1
    x *= 2
  while x>=2:
    res += 1
    x /= 2

  # Fractional part
  fp = 1.0
  while fp>=tol:
    fp /= 2
    x *= x
    if x >= 2:
        x /= 2
        res += fp

  return res

http://en.wikipedia.org/wiki/Binary_logarithm

def lg(x, tol=1e-13):
  res = 0.0

  # Integer part
  while x<1:
    res -= 1
    x *= 2
  while x>=2:
    res += 1
    x /= 2

  # Fractional part
  fp = 1.0
  while fp>=tol:
    fp /= 2
    x *= x
    if x >= 2:
        x /= 2
        res += fp

  return res

回答 5

>>> def log2( x ):
...     return math.log( x ) / math.log( 2 )
... 
>>> log2( 2 )
1.0
>>> log2( 4 )
2.0
>>> log2( 8 )
3.0
>>> log2( 2.4 )
1.2630344058337937
>>> 
>>> def log2( x ):
...     return math.log( x ) / math.log( 2 )
... 
>>> log2( 2 )
1.0
>>> log2( 4 )
2.0
>>> log2( 8 )
3.0
>>> log2( 2.4 )
1.2630344058337937
>>> 

回答 6

试试这个 ,

import math
print(math.log(8,2))  # math.log(number,base) 

Try this ,

import math
print(math.log(8,2))  # math.log(number,base) 

回答 7

logbase2(x)= log(x)/ log(2)

logbase2(x) = log(x)/log(2)


回答 8

在python 3或更高版本中,math类具有休闲功能

import math

math.log2(x)
math.log10(x)
math.log1p(x)

或者您通常可以将其math.log(x, base)用于任何所需的基础。

In python 3 or above, math class has the fallowing functions

import math

math.log2(x)
math.log10(x)
math.log1p(x)

or you can generally use math.log(x, base) for any base you want.


回答 9

log_base_2(x)= log(x)/ log(2)

log_base_2(x) = log(x) / log(2)


回答 10

不要忘记,日志[基A] X =日志[底座B]×/日志[基B]甲

因此,如果您仅拥有log(用于自然对数)和log10(用于以10为底的对数),则可以使用

myLog2Answer = log10(myInput) / log10(2)

Don’t forget that log[base A] x = log[base B] x / log[base B] A.

So if you only have log (for natural log) and log10 (for base-10 log), you can use

myLog2Answer = log10(myInput) / log10(2)

ValueError:数学域错误

问题:ValueError:数学域错误

我只是从“ 使用Python进行工程中的数值方法”中测试一个示例。

from numpy import zeros, array
from math import sin, log
from newtonRaphson2 import *

def f(x):
    f = zeros(len(x))
    f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0
    f[1] = 3.0*x[0] + 2.0**x[1] - x[2]**3 + 1.0
    f[2] = x[0] + x[1] + x[2] -5.0
    return f

x = array([1.0, 1.0, 1.0])
print newtonRaphson2(f,x)

当我运行它时,它显示以下错误:

File "example NR2method.py", line 8, in f
    f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0
ValueError: math domain error

我将其范围缩小到了日志,因为当我删除日志并添加其他功能时,它可以工作。我认为这是由于对底座的某种干扰,我不知道怎么做。谁能提出解决方案?

I was just testing an example from Numerical Methods in Engineering with Python.

from numpy import zeros, array
from math import sin, log
from newtonRaphson2 import *

def f(x):
    f = zeros(len(x))
    f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0
    f[1] = 3.0*x[0] + 2.0**x[1] - x[2]**3 + 1.0
    f[2] = x[0] + x[1] + x[2] -5.0
    return f

x = array([1.0, 1.0, 1.0])
print newtonRaphson2(f,x)

When I run it, it shows the following error:

File "example NR2method.py", line 8, in f
    f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0
ValueError: math domain error

I have narrowed it down to the log as when I remove log and add a different function, it works. I assume it is because of some sort of interference with the base, I can’t figure out how. Can anyone suggest a solution?


回答 0

您的代码执行log的a小于或等于零。这在数学上是未定义的,因此Python的log函数引发了一个异常。这是一个例子:

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    log(-1)
ValueError: math domain error

在不知道newtonRaphson2函数作用的情况下,我不确定是否可以猜出无效x[2]值的来源,但希望这将引导您走上正确的道路。

Your code is doing a log of a number that is less than or equal to zero. That’s mathematically undefined, so Python’s log function raises an exception. Here’s an example:

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    log(-1)
ValueError: math domain error

Without knowing what your newtonRaphson2 function does, I’m not sure I can guess where the invalid x[2] value is coming from, but hopefully this will lead you on the right track.


回答 1

您正在尝试对非正数做对数。

对数在被赋予一个数字和被赋予的底数后找出底数。log(0)意味着某种提升力量的东西20。指数永远不会导致0*,这意味着log(0)没有答案,因此抛出math domain error

*注意:0^0可以产生0,但也可以同时产生1。这个问题被激烈参数。

You are trying to do a logarithm of something that is not positive.

Logarithms figure out the base after being given a number and the power it was raised to. log(0) means that something raised to the power of 2 is 0. An exponent can never result in 0*, which means that log(0) has no answer, thus throwing the math domain error

*Note: 0^0 can result in 0, but can also result in 1 at the same time. This problem is heavily argued over.


回答 2

您也可以使用math.log1p

根据官方文件

math.log1p(x)

返回1 + x(以e为底)的自然对数。对x接近零的结果进行精确计算。

您可以转换回原始值,并使用math.expm1该原始值将e乘幂x减1。

You may also use math.log1p.

According to the official documentation :

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

You may convert back to the original value using math.expm1 which returns e raised to the power x, minus 1.


回答 3

您由于以下任一原因而遇到数学域错误:您试图在对数函数中使用负数或零值。

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.


“ log”和“ symlog”有什么区别?

问题:“ log”和“ symlog”有什么区别?

matplotlib中,我可以使用pyplot.xscale()或设置轴缩放Axes.set_xscale()。这两个函数接受三个不同的尺度:'linear'| 'log'| 'symlog'

'log'和之间有什么区别'symlog'?在我做的一个简单测试中,它们看起来完全一样。

我知道文档说它们接受不同的参数,但是我仍然不了解它们之间的区别。有人可以解释一下吗?如果有一些示例代码和图形,答案将是最好的!(另:“符号”的名称从何而来?)

In matplotlib, I can set the axis scaling using either pyplot.xscale() or Axes.set_xscale(). Both functions accept three different scales: 'linear' | 'log' | 'symlog'.

What is the difference between 'log' and 'symlog'? In a simple test I did, they both looked exactly the same.

I know the documentation says they accept different parameters, but I still don’t understand the difference between them. Can someone please explain it? The answer will be the best if it has some sample code and graphics! (also: where does the name ‘symlog’ come from?)


回答 0

我终于找到了一些时间来做一些实验,以了解它们之间的区别。这是我发现的:

  • log仅允许使用正值,并允许您选择如何处理负值(maskclip)。
  • symlog表示对数对称,并允许正值和负值。
  • symlog 允许在绘图内将范围设置为零左右,而不是对数,而是线性的。

我认为通过图形和示例,一切都将变得更容易理解,因此让我们尝试一下:

import numpy
from matplotlib import pyplot

# Enable interactive mode
pyplot.ion()

# Draw the grid lines
pyplot.grid(True)

# Numbers from -50 to 50, with 0.1 as step
xdomain = numpy.arange(-50,50, 0.1)

# Plots a simple linear function 'f(x) = x'
pyplot.plot(xdomain, xdomain)
# Plots 'sin(x)'
pyplot.plot(xdomain, numpy.sin(xdomain))

# 'linear' is the default mode, so this next line is redundant:
pyplot.xscale('linear')

# How to treat negative values?
# 'mask' will treat negative values as invalid
# 'mask' is the default, so the next two lines are equivalent
pyplot.xscale('log')
pyplot.xscale('log', nonposx='mask')

# 'clip' will map all negative values a very small positive one
pyplot.xscale('log', nonposx='clip')

# 'symlog' scaling, however, handles negative values nicely
pyplot.xscale('symlog')

# And you can even set a linear range around zero
pyplot.xscale('symlog', linthreshx=20)

为了完整起见,我使用以下代码保存每个图:

# Default dpi is 80
pyplot.savefig('matplotlib_xscale_linear.png', dpi=50, bbox_inches='tight')

请记住,您可以使用以下方法更改图形尺寸:

fig = pyplot.gcf()
fig.set_size_inches([4., 3.])
# Default size: [8., 6.]

(如果您不知道我的回答我的问题,请阅读

I finally found some time to do some experiments in order to understand the difference between them. Here’s what I discovered:

  • log only allows positive values, and lets you choose how to handle negative ones (mask or clip).
  • symlog means symmetrical log, and allows positive and negative values.
  • symlog allows to set a range around zero within the plot will be linear instead of logarithmic.

I think everything will get a lot easier to understand with graphics and examples, so let’s try them:

import numpy
from matplotlib import pyplot

# Enable interactive mode
pyplot.ion()

# Draw the grid lines
pyplot.grid(True)

# Numbers from -50 to 50, with 0.1 as step
xdomain = numpy.arange(-50,50, 0.1)

# Plots a simple linear function 'f(x) = x'
pyplot.plot(xdomain, xdomain)
# Plots 'sin(x)'
pyplot.plot(xdomain, numpy.sin(xdomain))

# 'linear' is the default mode, so this next line is redundant:
pyplot.xscale('linear')

# How to treat negative values?
# 'mask' will treat negative values as invalid
# 'mask' is the default, so the next two lines are equivalent
pyplot.xscale('log')
pyplot.xscale('log', nonposx='mask')

# 'clip' will map all negative values a very small positive one
pyplot.xscale('log', nonposx='clip')

# 'symlog' scaling, however, handles negative values nicely
pyplot.xscale('symlog')

# And you can even set a linear range around zero
pyplot.xscale('symlog', linthreshx=20)

Just for completeness, I’ve used the following code to save each figure:

# Default dpi is 80
pyplot.savefig('matplotlib_xscale_linear.png', dpi=50, bbox_inches='tight')

Remember you can change the figure size using:

fig = pyplot.gcf()
fig.set_size_inches([4., 3.])
# Default size: [8., 6.]

(If you are unsure about me answering my own question, read this)


回答 1

symlog类似于log,但是允许您定义一个接近零的值范围,在该范围内绘图是线性的,以避免使绘图在零附近变为无穷大。

来自http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xscale

在对数图中,永远不会有零值,并且如果您的值接近零,它将从图的底部向下(无限向下)尖峰,因为当您采用“ log(逼近零)”时,得到“接近负无穷大”。

symlog将在需要创建对数图的情况下为您提供帮助,但是当值有时可能会下降到零或下降到零时,但是您仍然希望能够以有意义的方式在图上显示该值。如果您需要符号记录,就可以知道。

symlog is like log but allows you to define a range of values near zero within which the plot is linear, to avoid having the plot go to infinity around zero.

From http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xscale

In a log graph, you can never have a zero value, and if you have a value that approaches zero, it will spike down way off the bottom off your graph (infinitely downward) because when you take “log(approaching zero)” you get “approaching negative infinity”.

symlog would help you out in situations where you want to have a log graph, but when the value may sometimes go down towards, or to, zero, but you still want to be able to show that on the graph in a meaningful way. If you need symlog, you’d know.


回答 2

这是必须使用符号日志时的行为示例:

初始图,未缩放。注意多少点聚集在x〜0

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

[

对数比例图。一切都崩溃了。

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set(xlabel='Score, log', ylabel='Total Amount Deposited, log')

为什么会崩溃?由于x轴上的某些值非常接近或等于0。

符号比例图。一切都是应有的。

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

    ax.set_xscale('symlog')
    ax.set_yscale('symlog')
    ax.set(xlabel='Score, symlog', ylabel='Total Amount Deposited, symlog')

Here’s an example of behaviour when symlog is necessary:

Initial plot, not scaled. Notice how many dots cluster at x~0

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

[

Log scaled plot. Everything collapsed.

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set(xlabel='Score, log', ylabel='Total Amount Deposited, log')

Why did it collapse? Because of some values on the x-axis being very close or equal to 0.

Symlog scaled plot. Everything is as it should be.

    ax = sns.scatterplot(x= 'Score', y ='Total Amount Deposited', data = df, hue = 'Predicted Category')

    ax.set_xscale('symlog')
    ax.set_yscale('symlog')
    ax.set(xlabel='Score, symlog', ylabel='Total Amount Deposited, symlog')


在python中使用matplotlib绘制对数轴

问题:在python中使用matplotlib绘制对数轴

我想使用matplotlib绘制一个对数轴的图形。

我一直在阅读文档,但无法弄清楚语法。我知道这可能'scale=linear'与plot参数类似,但是我似乎无法正确理解

示例程序:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)
pylab.show()

I want to plot a graph with one logarithmic axis using matplotlib.

I’ve been reading the docs, but can’t figure out the syntax. I know that it’s probably something simple like 'scale=linear' in the plot arguments, but I can’t seem to get it right

Sample program:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)
pylab.show()

回答 0

您可以使用该Axes.set_yscale方法。这样,您可以在Axes创建对象后更改比例。这也将允许您构建一个控件,让用户根据需要选择比例。

要添加的相关行是:

ax.set_yscale('log')

您可以使用'linear'切换回线性刻度。您的代码如下所示:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)

ax.set_yscale('log')

pylab.show()

You can use the Axes.set_yscale method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.

The relevant line to add is:

ax.set_yscale('log')

You can use 'linear' to switch back to a linear scale. Here’s what your code would look like:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)

ax.set_yscale('log')

pylab.show()


回答 1

首先,混合pylabpyplot编码不是很整洁。而且,pyplot样式比使用pylab更为可取

这是一个仅使用pyplot函数的稍作清理的代码:

from matplotlib import pyplot

a = [ pow(10,i) for i in range(10) ]

pyplot.subplot(2,1,1)
pyplot.plot(a, color='blue', lw=2)
pyplot.yscale('log')
pyplot.show()

相关功能是pyplot.yscale()。如果使用面向对象的版本,请用方法替换它Axes.set_yscale()。请记住,您还可以使用pyplot.xscale()(或Axes.set_xscale())更改X轴的比例。

检查我的问题‘log’和’symlog’有什么区别?查看matplotlib提供的图形比例的一些示例。

First of all, it’s not very tidy to mix pylab and pyplot code. What’s more, pyplot style is preferred over using pylab.

Here is a slightly cleaned up code, using only pyplot functions:

from matplotlib import pyplot

a = [ pow(10,i) for i in range(10) ]

pyplot.subplot(2,1,1)
pyplot.plot(a, color='blue', lw=2)
pyplot.yscale('log')
pyplot.show()

The relevant function is pyplot.yscale(). If you use the object-oriented version, replace it by the method Axes.set_yscale(). Remember that you can also change the scale of X axis, using pyplot.xscale() (or Axes.set_xscale()).

Check my question What is the difference between ‘log’ and ‘symlog’? to see a few examples of the graph scales that matplotlib offers.


回答 2

您只需要使用符号学而不是情节:

from pylab import *
import matplotlib.pyplot  as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)

line, = ax.semilogy(a, color='blue', lw=2)
show()

You simply need to use semilogy instead of plot:

from pylab import *
import matplotlib.pyplot  as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)

line, = ax.semilogy(a, color='blue', lw=2)
show()

回答 3

如果要更改对数的底数,只需添加:

plt.yscale('log',basey=2) 
# where basex or basey are the bases of log

if you want to change the base of logarithm, just add:

plt.yscale('log',basey=2) 
# where basex or basey are the bases of log

回答 4

我知道这有点不合时宜,因为一些评论提到这ax.set_yscale('log')是“最好的”解决方案,我认为可能是反驳。我不建议将其ax.set_yscale('log')用于直方图和条形图。在我的版本(0.99.1.1)中,我遇到了一些渲染问题-不确定此问题的普遍性。但是,bar和hist都具有可选参数,可以将y比例设置为log,这很好用。

参考:http : //matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist

I know this is slightly off-topic, since some comments mentioned the ax.set_yscale('log') to be “nicest” solution I thought a rebuttal could be due. I would not recommend using ax.set_yscale('log') for histograms and bar plots. In my version (0.99.1.1) i run into some rendering problems – not sure how general this issue is. However both bar and hist has optional arguments to set the y-scale to log, which work fine.

references: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist


回答 5

因此,如果您只是像我经常那样使用简单的API(我在ipython中经常使用它),那么这很简单

yscale('log')
plot(...)

希望这可以帮助寻找简单答案的人!:)。

So if you are simply using the unsophisticated API, like I often am (I use it in ipython a lot), then this is simply

yscale('log')
plot(...)

Hope this helps someone looking for a simple answer! :).


回答 6

您可以使用以下代码:

np.log(df['col_whose_log_you_need']).iplot(kind='histogram', bins=100,
                                   xTitle = 'log of col',yTitle ='Count corresponding to column',
                                   title='Distribution of log(col_whose_log_you_need)')

You can use below code:

np.log(df['col_whose_log_you_need']).iplot(kind='histogram', bins=100,
                                   xTitle = 'log of col',yTitle ='Count corresponding to column',
                                   title='Distribution of log(col_whose_log_you_need)')