I would like to display a font in Times New Roman in the legend of a matplotlib plot.
I have changed all other tick labels/axis labels/titles to Times New Roman, and have searched the documentation but I can only find how to change the font size in a legend using the prop
argument in pyplot.legend()
Of course straight after posting, I found the answer. Solution for anyone else with the same issue:
import matplotlib as mpl
mpl.rc('font',family='Times New Roman')
This wasn't showing up in google results so I'm going to post it as an answer. The rc parameters for font can be used to set a single default font.
Solution for anyone else with the same issue:
import matplotlib as mpl
mpl.rc('font',family='Times New Roman')
The .rc solution given changes the default font for all drawing.
Here is a solution for doing this when you don't want to change all the fonts, but just the font properties of the legend of this particular graph (a legend belonging to a particular axis object):
L = ax.legend()
plt.setp(L.texts, family='Consolas')
This allows you to choose a different font for the legend and the axes. I found this helpful when I needed a monospace font for my legend, but not for the axes -- allowing me to create a neat legend like this:
Note how the title is a different font than the legend - this gives me an alignment of numbers that would otherwise be hard to achieve.
I think this is the better way.
import matplotlib.font_manager as fm
## your font directory
font_path = '/Users/frhyme/Library/Fonts/BMDOHYEON_otf.otf'
## font_name
font_name = fm.FontProperties(fname=font_path).get_name()
plt.legend(prop={'family':font_name, 'size':20})
Related
I made a calendar heatmap using calplot. The documentation for calplot is here: https://calplot.readthedocs.io/en/latest/.
I want to change the font of the title and labels, but do not know how to change the label font. I only managed to change the title font. Calplot is built upon matplotlib and it can pass on arguments to matplotlib.
First I exclusively focused on matplotlib and changed its font like this:
csfont = {'fontname':'Open Sans'}
hfont = {'fontname':'Open Sans'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
I then looked at the documentation of calplot and noticed the parameter suptitle_kws. I then tried to pass csfont as follows:
calplot.calplot(..., suptitle_kws=csfont)
And this correctly changed the title font. However, I also want to change the other fonts (of the weekdays and the colorbar). I don't know how to do this.
I’m trying to customise individual legend labels. In the example below, the legend contains two items. I’d like to make the text bold for only the second legend label.
Here’s a general outline of the code:
leg = plt.legend()
for text in leg.get_texts():
text.set_fontweight...
Here’s a runnable example:
import matplotlib.pyplot as plt
X=range(10)
Y=range(100,110)
Z=range(105,115)
plt.plot(X,Y,label='normal')
plt.plot(X,Z,label='bold')
fontweights=['normal','bold']
leg=plt.legend()
for fw,text in zip(fontweights,leg.get_texts()):
text.set_fontweight(fw)
plt.show()
Here's the output:
enter image description here
The plot produced shows that set_fontweight() changes both labels to bold. So is this a bug with set_fontweight(), or am I doing something wrong?
Similar functions, such as text.set_color(), can be used to modify legend labels individually.
Lastly, I’m using matplotlib version 3.2.2.
Thanks!
I have matplotlib 3.3.4 running, and get a bold and unbold legend entry - see attached image - so I think an upgrade should fix the problem.
Well , I am making some plots and wants to make everything in bold font. I can can use weight="bold" to make bold font of label to ticks. Can also use the prop={'weight':'bold'} to make the legends lines bold, but I can't make the legend title bold. So, 1st question is there a way to make the legend title bold?
2nd,I tried to used matplotlib latex support to make the title bold, that did it but if I use rc('text', usetex=True) I cant use weight=bold and have to use \textbf{} everytime, also how do I make the ticks bold in this way.
3rd , If I use latex support then the font changes that I don't like. How do use the normal matplotlib font with using latex?
Making everything bold is rather easy. Just add
plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"
at the top of the script.
import matplotlib.pyplot as plt
plt.rcParams["font.weight"] = "bold"
plt.rcParams["axes.labelweight"] = "bold"
plt.plot([2,3,1], label="foo")
plt.plot([3,1,3], label="bar")
plt.legend(title="Legend Title")
plt.xlabel("xLabel")
plt.show()
You should be able to pass parameters into the plt.legend using the prop argument
legend_prop = {'weight':'bold'}
plt.plot(x, y, label='some label')
plt.legend(prop=legend_prop)
This would give you bold labels. Is this not what you're looking for?
I am trying to change the font size of my x axis that happens to be strings and not numbers. I have changed other charts that have integers by using :
plt.xticks(size=10)
However, this dose not work for some of my graphs that have months in the place of integers. Keep in mind i am not using subplots.
Try setting the fontsize either by using the the fontsize keyword argument or if you want to globally change it to every plot in your script by updating the rcParams as
import matplotlib
matplotlib.rc('xtick', labelsize=20)
Also look at this answer: How to change the font size on a matplotlib plot
Or here: How can I change the font size of ticks of axes object in matplotlib
I have a problem which I thought would be more occurring. However, after scouring the internet for some time now I have not been able to find the solution to my problem. So here it goes:
For a plot, created using matplotlib.pyplot I want to incorporate the SI-unit micro meter into my xlabel. The unit micro meter however needs to be upright. After some fiddling around I achieved the desired xlabel.
The code that I have to generate this is:
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('text', usetex = True)
params = {'text.latex.preamble': [r'\usepackage{siunitx}', r'\usepackage{cmbright}']}
plt.rcParams.update(params)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('$\si{\micro \meter}$', fontsize = 16)
ax.set_ylabel("hi", fontsize = 16)
plt.savefig("test.png")
The result is shown below:
The micro meter is exactly as I want it to be. The problem however is that the font of the x and y ticks is altered. This is because of:
matplotlib.rc('text', usetex = True)
How can I reset the font values to their original values? Or how can I make sure the fonts are not changed when introducing tex?
As a reference, the original values I am referring to look like this:
Besides trying to revert the fonts back to their original values I also tried different methods of incorporating micro meter into my xlabel. The problem that arises here is that I it remains italic or it has a bold type setting. The micro meter I am looking for is the one given in the first figure.
I hope someone can help me solve this problem.
Thanx in advance
What worked for me was not to usetex, but to use Unicode:
ax.set_xlabel(u'\u03bc')
sets the label as a single upright mu.
This requires the following settings when loading matplotlib:
import matplotlib
matplotlib.rcParams['mathtext.fontset'] = 'cm'
matplotlib.rc('font', family='serif', serif='CMU Serif')
import matplotlib.pyplot as plt
Here I'm using the "Computer Modern Unicode" font from Sourceforge (highly recommended if you'd like consistency with writing typeset in LaTeX and its default Computer Modern font).
But any unicode font with the mu glyph should work. Actually, the mu from CMU Serif is not as aesthetically nice as the mu from SIunitx, but it is correct.
Python needed to be restarted for that to take effect.
I am also struggling with such a problem, i.e. getting the tick labels and axes labels to be consistent when text.usetex = True. The solution that I have managed to find it not ideal, but it works for the moment.
What you have to do is set the font family to "sans-serif" and also add a latex package that uses sans-serif math fonts (sfmath -- make sure it is in your tex path!)
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('text', usetex = True)
matplotlib.rc('font', **{'family':"sans-serif"})
params = {'text.latex.preamble': [r'\usepackage{siunitx}',
r'\usepackage{sfmath}', r'\sisetup{detect-family = true}',
r'\usepackage{amsmath}']}
plt.rcParams.update(params)
fig = plt.figure(figsize = (4,4))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('$\si{\um} detection$')
ax.set_ylabel(r"$\mu \boldsymbol{\mu}$")
plt.show()
In addition, I had to tell the siunitx package to detect the font family, and I also had to add some additional text to the x-label in order for the detection to actually work (you can remove this text later and the label will still work after that).
For me this results in:
More generally, I have the following my ~/.matplotlib/matploblibrc file, for serif fonts:
font.family : serif
text.latex.preamble : \usepackage{mathptmx}
and for sans-serif:
font.family : sans-serif
text.latex.preamble : \usepackage{sfmath}
I had the same problem and this solved it:
In your matplotlibrc file change
mathtext.default : it
to
mathtext.default : regular