python: scatter plot logarithmic scale

PythonMatplotlibLogarithm

Python Problem Overview


In my code, I take the logarithm of two data series and plot them. I would like to change each tick value of the x-axis by raising it to the power of e (anti-log of natural logarithm).

In other words. I want to graph the logarithms of both series but have x-axis in levels.

enter image description here

Here is the code that I'm using.

from pylab import scatter
import pylab
import matplotlib.pyplot as plt
import pandas as pd
from pandas import Series, DataFrame
import numpy as np

file_name = '/Users/joedanger/Desktop/Python/scatter_python.csv'

data = DataFrame(pd.read_csv(file_name))

y = np.log(data['o_value'], dtype='float64')
x = np.log(data['time_diff_day'], dtype='float64')

fig = plt.figure()
plt.scatter(x, y, c='blue', alpha=0.05, edgecolors='none')
fig.suptitle('test title', fontsize=20)
plt.xlabel('time_diff_day', fontsize=18)
plt.ylabel('o_value', fontsize=16)
plt.xticks([-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4])

plt.grid(True)
pylab.show()

Python Solutions


Solution 1 - Python

let matplotlib take the log for you:

fig = plt.figure()
ax = plt.gca()
ax.scatter(data['o_value'] ,data['time_diff_day'] , c='blue', alpha=0.05, edgecolors='none')
ax.set_yscale('log')
ax.set_xscale('log')

If you are using all the same size and color markers, it is faster to use plot

fig = plt.figure()
ax = plt.gca()
ax.plot(data['o_value'] ,data['time_diff_day'], 'o', c='blue', alpha=0.05, markeredgecolor='none')
ax.set_yscale('log')
ax.set_xscale('log')

Solution 2 - Python

The accepted answer is a bit out of date. At least pandas 0.25 natively supports log axes:

# logarithmic X
df.plot.scatter(..., logx=True)
# logarithmic Y
df.plot.scatter(..., logy=True)
# both
df.plot.scatter(..., loglog=True)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnatsuki_2002View Question on Stackoverflow
Solution 1 - PythontacaswellView Answer on Stackoverflow
Solution 2 - PythonMaratView Answer on Stackoverflow