Skip to content Skip to sidebar Skip to footer

Logarithmic Scale In Python

I am Trying to plot a graphic in logarithmic scale (Y axis) but I need to show in the Y axis all the original values. I used the code: # -*- coding: utf-8 -*- import math import m

Solution 1:

Matplotlib ticker formatting is what you're looking for:

from matplotlib.ticker import FormatStrFormatter

...

plt.yscale('log')
plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.d')) #Here!
plt.ylim(ymax=sorted(y)[-1]+1) # valor maximo do eixo y

plt.show()

Though there may be a simpler way. Found using matplotlibs tick formatting documentation

Solution 2:

The question seems to be how to show all y values which are present as bars on the y axis, given the y axis being a logarithmic scale.

While this may not make too much sense, because of overlapping labels, here is the answer:

You may use a FixedLocator to set the positions of the labels and a ScalarFormatter to set the format to normal decimal numbers (instead of powers of 10).

plt.gca().yaxis.set_major_locator(matplotlib.ticker.FixedLocator(np.unique(y)))
plt.gca().yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())

Complete code:

import matplotlib.pyplot as plt
import matplotlib.dates as dates
import matplotlib.ticker
from datetime import datetime, timedelta
import numpy as np 

x,y = np.loadtxt(io.StringIO(u), delimiter=",", unpack=True)

x1 = [str(datetime.fromtimestamp(int(d)))[-8:] for d in x]
y_pos = [idx for idx, i inenumerate(y)]

plt.figure(figsize=(17,9))
plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%m/%d/%Y %H:%M:%S'))

plt.bar(y_pos, y, align='edge', color="blue", alpha=0.5, width=0.5) 
plt.title("Values X Time")
plt.ylabel("Values")
plt.xlabel('Time')
plt.xticks(y_pos, x1, size='small',rotation=35, ha="right")

plt.yscale('log')
plt.ylim(ymax=sorted(y)[-1]+1) # valor maximo do eixo y

plt.gca().yaxis.set_major_locator(matplotlib.ticker.FixedLocator(np.unique(y)))
plt.gca().yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())

plt.show()

enter image description here

Solution 3:

You can specify ether the x or y tick locations. To add the maximum value to the y axis use .yticks().

plt.yscale('log')
plt.yticks([1,10,100] + [max(y)])
plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.d'))

To determine the major ticks for a log scale at runtime; find the maximum power of ten in the data, then make all the powers of ten below it.:

import math
...
exp = int(math.log10(max(y)))
majors = [10**x for x in range(exp+1)]
#majors = [10**n for n in range(len(str(max(y))))]
plt.yticks(majors + [max(y)])

Solution 4:

Funny, I solved exactly this problem in the SO in portuguese.

In addition to the answer of ImportanceOfBeingErnest, you can add

plt.gca().minorticks_off()

to remove the minor ticks of the log scale, as they are overlapping. As i believe that this remove all minor ticks, you can use another approach:

matplotlib.rcParams['xtick.minor.size'] = 0
matplotlib.rcParams['xtick.minor.width'] = 0

Or any of the other solutions mentioned in this question.

Post a Comment for "Logarithmic Scale In Python"