log plot with positive and negative data with negative power

26 次查看(过去 30 天)
Consider the followings:
x=[1 2 3 4]
y1=[1000, 50, -10, -1000]
y2=[1e-1, 5e-3, -1e-3, -1e-1]
Goal is to plot y vs. x with a logscale for y values.However Matlab loglog plot does not work with negative values. I know how to do it for y1 vs x. I am looking for help for y2 vs. x.
For y1 vs. x (where y values are positive or negative numbers, but the power is positive, 10^3 or -10^3 for example)
y1_log = sign(y1).*log10(abs(y1)); %that gives [3, 1.7, -1, -3]
Plot(x,y1_log)
% to change y labels:
c= get(gca,'ytick');
set(gca,'yticklabel',sign(c).*10.^abs(c));
For y2 vs. x (y values are positive or negative numbers, but the power is negative, 10^-3 or -10^-3 for example) The previous procedure can't help
y2_log = sign(y2).*log10(abs(y2)) %that gives [-1, -2.3, +3, +1]
Any suggestion on how to plot y2. vs. x, and also how to set appropriate ticks and labels for y axis?
  2 个评论
Guillaume
Guillaume 2015-4-30
It's not just matlab that does not work with negative values for logarithms, it's the whole of math. Logarithms are only defined over the range [0, Inf].
Whatever it is you're plotting with your code, it is not a logarithm anymore. In your first example, using -1 to represent the logarithm of -10 is just wrong. -1 is the logarithm of 0.1.
Lily
Lily 2015-4-30
I understand that log is defined for above 0. But there are cases where there are both very small and very large changes in y. What is your suggestion to capture all those changes in one graph? I have seen papers using log scale with both negative and positive data .

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2015-4-30
编辑:Stephen23 2016-7-20
One way to solve this would be to plot the positive and (absolute) negative values in two separate axes. This would require:
  • Use logical indexing to identify the positive and negative values.
  • plot positive and abs(negative) each on their own log-axes.
  • the "negative" axes are flipped along the Y direction.
  • the axes' position within the figure are adjusted so that the two axes butt against one another.
  • Some fiddling with the X-range to make them match up...
  • and some fiddling with the negative Y-labels.
  • done!
While it seems like a lots of work, in fact there are several advantages: the Y-ranges are completely independent, and can be still set to adjust automatically with new data, they can use the inbuilt axis labels and tickmarks, the data is plotted with exactly the values.

类别

Help CenterFile Exchange 中查找有关 Log Plots 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by