Hemmelig
Hemmelig

Reputation: 794

Logarithmic scale with decimal numbers in Matplotlib

I am using panda and Matplotlib together and have an x-scale based on the powers of 2. I would therefore love to use the logarithmic scale, but want to preserve the decimal numbers and not the scientific notation.

That code part looks like that:

df_list[count].plot(ax=axes[count], xticks=[16, 32, 64], logx=True, yticks=np.arange(0.4, 1.1, 0.1), title=lang_list[count], legend=None)

So I use xticks for the scale and lox=True for the logarithmic scale. Unfortunately, my scale now has the labels: 1.6x10^1, 3.2x10^1, 6.4x10^1

Is there any clever workaround?

Upvotes: 1

Views: 2285

Answers (1)

Ralubrusto
Ralubrusto

Reputation: 1501

Using some random data just for ilustration, you can do something like:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

df = pd.DataFrame({'Data': np.arange(1,1000)})

fig, ax = plt.subplots()
df['Data'].plot()
plt.xscale('log', base=2)  # This way you don't need to set ticks manually
ax.xaxis.set_major_formatter(ticker.ScalarFormatter())
plt.ticklabel_format(axis='x', style='plain')
plt.show()

I've used the plt.xscale command to set automatically the ticks for the x axis, but if you set them manually as you did this should work as well. The output is as follows

Image with correct x axis (without scientific notation)

Upvotes: 2

Related Questions