Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

python - How to extend non-log x axis of ln(x) plot

I would like to calculate several functions including ln(x) on an interval going from 1 to 10. However, I would like to plot on an interval of x ranging from x[-1, 10]. So far, I could not modify the ticks as I want, the labels are following the size of my ln(x) rather than the value of x itself:

axiss = np.linspace(-1,10,12)
x = np.linspace(-1, 10, 1002)
s = int(np.where(x == 1)[0])

fig, ax = plt.subplots()

ax.plot(np.log(x[s:-1]), label='ln(x)')
ax.plot(1/x[s:-1], label='1/x')
ax.plot(-1/(x[s:-1]**2), label='-1/x2')
ax.plot(2/(x[s:-1]**3), label='2/x3')
ax.legend()

ax.set_xlim(-100, 1000)
ax.set_xticklabels(axiss)

How could I do to define a range for my x-axis, but only calculate the functions on a part of it ?

I tried:

ax.plot(x, np.log(x[s:-1]), label='ln(x)')

but of course I have a length issue.

Thank you !

ps: yes I already searched online for ways to do it, asking here is the last resort that I have

question from:https://stackoverflow.com/questions/65926352/how-to-extend-non-log-x-axis-of-lnx-plot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can explicity give both x and y lists to matplotlib. This also avoids the need to set the xtick labels manually.

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 10, 1001)  # don't divide by 0.0
x_for_ln = np.linspace(0.001, 10, 1001)

fig, ax = plt.subplots()

ax.plot(x_for_ln, np.log(x_for_ln), label='ln(x)')
ax.plot(x, 1/x, label='1/x')
ax.plot(x, -1/(x**2), label='-1/x2')
ax.plot(x, 2/(x**3), label='2/x3')
ax.legend()
ax.set_ylim(-10, 10)

Plot generated by code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...