Reputation:
Here I need to plot a frequency and a simple line with a slope of -5/3.
The problem is that the main plot is using plt.loglog()
and when I want to show the line it gives me nothing or something strange.
Here are the pictures of it. I have plotted the right one and desired is the left one.
I already used np.linspace
and some other things, but I was not able to solve the problem. Also, it is not clear at which points I have the first and the end of the frequency plot. That's another reason why I can not use 'np.linspace'. Can anyone help me?
Upvotes: 0
Views: 2512
Reputation:
Thanks a lot for your attention. I tried your code but I found out maybe there are better ways to do it with kind of my dataset. So I did this:
np.array()
and had np.log()
function on it:x = ... # type(x) = list
y = ... # type(y) = list
.
.
.
x = np.log(np.array(x))
y = np.log(np.array(y))
In this case I did not have to use plt.loglog()
or np.log()
and np.exp()
in calculations anymore.
ymin, ymax = ([y.min(), y.max()])
ymid = (ymin + ymax) / 2
xmin, xmax = ([x.min(), x.max()])
xmid = (xmin + xmax) / 2
np.linspace()
for rest:slope = - 5 / 3
x1 = np.linspace(xmin, xmax)
y1 = slope * (x1 - xmid) + ymid
ax.plot(x1, y1, 'r')
And got the result I wanted.
the result
plt.loglog()
kind of plots in frequency spectrums, I edited these things:
np.array()
x = array(...)
y = array(...)
np.exp()
:ymin, ymax = log([y.min(), y.max()])
ymid = (ymin + ymax) / 2
xmin, xmax = log([x.min(), x.max()])
xmid = (xmin + xmax) / 2
slope = - 5 / 3
y1 = slope * (xmin - xmid) + ymid
y2 = slope * (xmax - xmid) + ymid
ax.plot(exp([xmin, xmax]), exp([y1, y2]), 'r')
plt.loglog()
the result
As you see now we have the plot in log scale.
Upvotes: 1
Reputation: 80299
Here is a possible approach. All calculations happen in logspace. The points are transformed back to linear space to be plotted. As matplotlib plots a line given two points always as straight, independent to the tranformation of the axes, only two points are needed.
Steps:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8, 8))
# first create some toy data roughly resembling the example plot
x = np.linspace(10, 2000, 1000)
y = np.random.normal(2000 / x ** np.linspace(.7, .55, x.size), 100 / x ** .7)
ax.plot(x, y)
y0, y1 = np.log([y.min(), y.max()])
# mid_x, mid_y = np.log([x[x.size // 2], y[y.size // 2]])
mid_x, mid_y = (np.log(x.min()) + np.log(x.max())) / 2, (y0 + y1) / 2
slope = -5 / 3
x0 = mid_x + slope * (y0 - mid_y)
x1 = mid_x + slope * (y1 - mid_y)
ax.plot(np.exp([x0, x1]), np.exp([y0, y1]), color='crimson')
plt.loglog()
plt.show()
Upvotes: 0