matplotlib: bold tick labels with scientific notation - python

I want to have bold tick labels with LaTeX-fonts in matplotlib. A sample plot can be found here:
sample plot
The code I am using:
import matplotlib as mpl
import matplotlib.pyplot as plt
f=plt.figure(figsize=(10,10))
ax = f.add_subplot(111)
x_data = [x for x in range(0, 200)]
y_data = [pow(x,6) for x in x_data]
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.rc('font', size=24)
plt.rc('font', weight='bold')
plt.grid(True)
p3, = plt.plot(x_data,y_data,'g',linewidth = 7,ls='dashed',markersize=8,markeredgewidth=8)
ax.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))
mpl.ticker.ScalarFormatter(useMathText = True)
plt.show()
The problem is, I would like to have the 1e13 in the upper corner to be displayed as $10^13$ as it would be if I leave out
mpl.ticker.ScalarFormatter(useMathText = True)
but then it is not in bold font. Is there any way to do this? I know that I could to all kind of tweaking with the original data by hand, but I would be totally happy to have an automatic solution.
And related to this question, I found the following thread:
matplotlib: format axis offset-values to whole numbers or specific number
There Joe Kington wrote a class FixedOrderFormatter(ScalarFormatter), which allows to change the power from 1e13 to 1e14, for example. Is there maybe even a way to combine the FixedOrderFormatter with the scientific notation to be $10^14$ with bold font instead of 1e14?

Related

How to use a colored shape as yticks in matplotlib or seaborn?

I am working on a task called knowledge tracing which estimates the student mastery level over time. I would like to plot a similar figure as below using the Matplotlib or Seaborn.
It uses different colors to represent a knowledge concept, instead of a text. However, I have googled and found there is no article is talking about how we can do this.
I tried the following
# simulate a record of student mastery level
student_mastery = np.random.rand(5, 30)
df = pd.DataFrame(student_mastery)
# plot the heatmap using seaborn
marker = matplotlib.markers.MarkerStyle(marker='o', fillstyle='full')
sns_plot = sns.heatmap(df, cmap="RdYlGn", vmin=0.0, vmax=1.0)
y_limit = 5
y_labels = [marker for i in range(y_limit)]
plt.yticks(range(y_limit), y_labels)
Yet it simply returns the __repr__ of the marker, e.g., <matplotlib.markers.MarkerStyle at 0x1c5bb07860> on the yticks.
Thanks in advance!
While How can I make the xtick labels of a plot be simple drawings using matplotlib? gives you a general solution for arbitrary shapes, for the shapes shown here, it may make sense to use unicode symbols as text and colorize them according to your needs.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(42)
fig, ax = plt.subplots()
ax.imshow(np.random.rand(3,10), cmap="Greys")
symbolsx = ["⚪", "⚪", "⚫", "⚫", "⚪", "⚫","⚪", "⚫", "⚫","⚪"]
colorsx = np.random.choice(["#3ba1ab", "#b43232", "#8ecc3a", "#893bab"], 10)
ax.set_xticks(range(len(symbolsx)))
ax.set_xticklabels(symbolsx, size=40)
for tick, color in zip(ax.get_xticklabels(), colorsx):
tick.set_color(color)
symbolsy = ["◾", "◾", "◾"]
ax.set_yticks(range(len(symbolsy)))
ax.set_yticklabels(symbolsy, size=40)
for tick, color in zip(ax.get_yticklabels(), ["crimson", "gold", "indigo"]):
tick.set_color(color)
plt.show()

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.

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')

Inconsistent font size for scientific notation in axis

I'm trying to make a plot for which the x axis will show in scientific notation. The way I found how to do so is to use the ticklabel_format function. Unfortunately this does not respect the font size I assign to the numbers shown in the axis, see image below:
The 1e-12 and 1e4 are displayed in a different font size even though I set equal label sizes.
How could I fix this? (A MWE is below)
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 10000.0, 10.)
s = np.sin(np.pi*t)*np.exp(-t*0.0001)
fig, ax = plt.subplots()
ax.tick_params(axis='both', which='major', labelsize=7)
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0), labelsize=7)
plt.plot(t,s)
plt.show()
According to ticklabel_format documentation, the function does not accept labelsize parameter.
You can change the font size using matplotlib.rc:
plt.rc('font', size=7)
I think this will help you, without change the global setting:
ax.yaxis.get_offset_text().set_fontsize(size)
I guess it's because that scientific representation is not treated as tick label, you can use:
import matplotlib
matplotlib.rc('font', size=7)
or
matplotlib.rcParams['font.size']=7
and remove labelsize=7 in ax.tick_params

Matplotlib: disable powers of ten in log plot

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()

Categories

Resources