Matplotlib: disable powers of ten in log plot - python

Is there a simple way to make matplotlib not show the powers of ten in a log plot, and instead just show the numbers? I.e., instead of [10^1, 10^2, 10^3] display [10, 100, 1000]? I don't want to change the tickmark locations, just want to get rid of the powers of ten.
This is what I currently have:
I can change the labels themselves via xticks, however I then get mismatching fonts or sizes for the y tick labels. I am using TeX for this text. I've tried the following:
xx, locs = xticks()
ll = [r'\rm{%s}' % str(a) for a in xx]
xticks(xx, ll)
This gives the following result:
In this particular case, I could use the same LaTeX roman font, but the sizes and looks are different to those in the y axis. Plus, if I used a different LaTeX font in matplotlib this is going to be problematic.
Is there a more flexible way of switching off the power of ten notation?

Use a ScalarFormatter:
from matplotlib import rc
rc('text', usetex=True)
rc('font', size=20)
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111)
ax.semilogx(range(100))
ax.xaxis.set_major_formatter(ScalarFormatter())
plt.show()

Related

pyplot order of magnitude fontsize modification when using scientific ticks python [duplicate]

I am attempting to plot differential cross-sections of nuclear decays and so the magnitudes of the y-axis are around 10^-38 (m^2) pylab as default plots the axis as 0.0,0.2,0.4... etc and has a '1e-38' at the top of the y-axis.
I need to increase the font size of just this little bit, I have tried adjusting the label size
py.tick_params(axis='y', labelsize=20)
but this only adjusts the labels 0.0,0.2,0.4....
Many thanks for all help
You can access the text object using the ax.yaxis.get_offset_text().
import numpy as np
import matplotlib.pyplot as plt
# Generate some data
N = 10
x = np.arange(N)
y = np.array([i*(10**-38) for i in x])
fig, ax = plt.subplots()
# Plot the data
ax.plot(x,y)
# Get the text object
text = ax.yaxis.get_offset_text()
# Set the size.
text.set_size(30) # Overkill!
plt.show()
I've written the solution above using matplotlib.pyplot rather than pylab though if you absolutely have to use pylab then it can be changed (though I'd recommend you use matplotlib.pyplot in any case as they are pretty much identical you can just do a lot more with pyplot easier).
Edit
If you were to use pylab then the code would be:
pylab.plot(x, y)
ax = pylab.gca() # Gets the current axis object
text = ax.yaxis.get_offset_text() # Get the text object
text.set_size(30) # # Set the size.
pylab.show()
An example plot with an (overkill!) offset text.

How do I increase the infinity symbol in matplotlib labels

Consider the illustrative example below:
from matplotlib import pyplot as plt
x=list(range(5))
xticks=x.copy()
xlabels=x.copy()
xlabels[-1] = r"$\infty$"
fig, axes = plt.subplots()
axes.plot(x)
axes.set_xticks(xticks)
axes.set_xticklabels(xlabels, fontsize=20)
This produces the following figure
I want to make the infinity sign larger in relation to the numbers in the x labels. It is too small in the way matplotlib plots it. Everything that I've tried to increase its size also increases the sizes of the numbers in the label.
How can I do that?
Thanks
Try this, grab the last element in the xticklabels array and use set_fontsize on that element:
from matplotlib import pyplot as plt
x=list(range(5))
xticks=x.copy()
xlabels=x.copy()
xlabels[-1] = r"$\infty$"
fig, axes = plt.subplots()
axes.plot(x)
axes.set_xticks(xticks)
axes.set_xticklabels(xlabels, fontsize=20)
axes.get_xticklabels()[-1].set_fontsize(26)
plt.show()
Output:

Have the same font for numbers on axis and for axis label in Matplotlib

I have the following code to create the plot depicted below:
import matplotlib.pyplot as plt
x = [...]
y = [...]
fig = plt.figure()
ax = fig.gca()
ax.set_xlabel(r'$\mathsf{Concentration [mol/m^{3}]}$')
ax.set_ylabel(r'$\mathsf{Diffusion Coefficient [m^2/s]}$')
plt.semilogy(x, y)
plt.grid(True, which="both")
plt.autoscale()
plt.savefig("coeff.pdf")
plt.show()
It's perfectly possible to use LaTeX math notation for the axis label. Unfortunately, the numbers at the ticks/grid lines have another font:
How can I make sure the axis labels and the numbers have the same font and style?
You need to set the mathtext font to the regular font:
from matplotlib import rcParams
rcParams['mathtext.default'] = 'regular'
This works for using mathtext for equation rendering. If you use Latex, you should take a look here.

Matplotlib, usetex: Colorbar's font does not match plot's font

I have a matplotlib plot with a colorbar and can't seem to figure out how to match the fonts of the plot and the colorbar.
I try to use usetex for text handling, but it seems like only the ticks of the plot are affected, not the ticks of the colorbar.
Also, I have searched for solution quite a bit, so in the following code sample, there are a few different attempts included, but the result still is a bold font. Minimum failing code sample:
import matplotlib as mpl
import matplotlib.pyplot as plt
import sys
import colorsys
import numpy as np
mpl.rc('text', usetex=True)
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.weight"] = 100
plt.rcParams["axes.labelweight"] = 100
plt.rcParams["figure.titleweight"] = 100
def draw():
colors = [colorsys.hsv_to_rgb(0.33, step /15, 1) for step in [2, 5, 8, 11, 14]]
mymap = mpl.colors.LinearSegmentedColormap.from_list('value',colors, N=5)
Z = [[0,0],[0,0]]
levels = range(2,15+4,3)
CS3 = plt.contourf(Z, levels, cmap=mymap)
plt.clf()
plt.figure(figsize=(20, 15))
plt.gca().set_aspect('equal')
cbar = plt.colorbar(CS3, ax=plt.gca(), shrink=0.5, fraction=0.5, aspect=30, pad=0.05, orientation="horizontal")
cbar.set_ticks([1.5 + x for x in [2,5,8,11,14]])
# attempts to make the fonts look the same
cbar.ax.set_xticklabels([1,2,3,4,5], weight="light", fontsize=16)
cbar.set_label("value", weight="ultralight", fontsize=32)
plt.setp(cbar.ax.xaxis.get_ticklabels(), weight='ultralight', fontsize=16)
for l in cbar.ax.xaxis.get_ticklabels():
l.set_weight("light")
plt.show()
draw()
Unfortunately, the fonts don't look the same at all. Picture:
I'm sure it's just a stupid misunderstanding of usetex on my part. Why does the usetex not seem to handle the colormap's font?
Thanks!
The issue here is that MPL wraps ticklabels in $ when usetex=True. This causes them to have different sizes than text that is not wrapped in $. When you force your ticks to be labeled with [1,2,3,4,5] these values are not wrapped in $, and are therefore rendered differently. I don't know the details of why this is, but I've run into the problem before myself.
I'd recommend wrapping your colorbar ticks in $, for example:
cbar.ax.set_xticklabels(['${}$'.format(tkval) for tkval in [1, 2, 3, 4, 5]])
From there you should be able to figure out how to adjust font sizes/weights so that they match and you get what you want.

Formatting part of text in Matplotlib in Python

I would like to change the fontweight of part of some text I give to matplotlib's text command on a plot using matplotlib. For example, I would like the first word to be bold. Also, I would like to change the font weight and font to Times New Roman without affecting the rest of the labels, i.e. x-axis and y-axis labels.
Browsing the stack exchange, I came across the rc('text', usetex=True) command. When I use this, these changes affect the entire plot (i.e., the x-axis and y-axis labels as well). I would just like to format the text given to matplotlib's text command. Is there a way to do this?
Here's an example:
import numpy as np
import matplotlib.pyplot as plt
randomNumber = []
for index in range(0, 1000):
np.random.seed()
randomNumber.append(np.random.normal(0, 1, 1)[0])
plt.figure()
ax = plt.gca()
ax.hist(randomNumber, 12)
#plt.figure()
#plt.plot()
plt.rc('text', usetex=True)
ax.text(-2, 150, '\\textbf{test} testing', fontsize=16, fontname='Times New Roman')

Categories

Resources