Following this example:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
for i, label in enumerate(('A', 'B', 'C', 'D')):
ax = fig.add_subplot(2,2,i+1)
ax.text(0.05, 0.95, label, transform=ax.transAxes,
fontsize=16, fontweight='bold', va='top')
plt.show()
I get this output:
Why are my labels normal weight, while the documentation shows this should create bold letters A, B, C, D?
I also get this warning:
Warning (from warnings module):
File "C:\Python27\lib\site-packages\matplotlib\font_manager.py", line 1228
UserWarning)
UserWarning: findfont: Could not match :family=Bitstream Vera Sans:style=italic:variant=normal:weight=bold:stretch=normal:size=x-small. Returning C:\Python27\lib\site-packages\matplotlib\mpl-data\fonts\ttf\Vera.ttf
OP Resolution
From a deleted answer posted by the OP on Sep 15, 2013
Ok, it was a problem with the installation of matplotlib
Try using weight instead of fontweight.
Maybe try using this -
plt.rcParams['axes.labelsize'] = 16
plt.rcParams['axes.labelweight'] = 'bold'
Do this at a global level in your program.
The example from your question works on my machine. Hence you definately have a library problem. Have you considered using latex to make bold text? Here an example
Code
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 1)
ax0, ax1, ax2 = axs
ax0.text(0.05, 0.95, 'example from question',
transform=ax0.transAxes, fontsize=16, fontweight='bold', va='top')
ax1.text(0.05, 0.8, 'you can try \\textbf{this} using \\LaTeX', usetex=True,
transform=ax1.transAxes, fontsize=16, va='top')
ax2.text(0.05, 0.95,
'or $\\bf{this}$ (latex math mode with things like '
'$x_\mathrm{test}^2$)',
transform=ax2.transAxes, fontsize=10, va='top')
plt.show()
Not sure if you're still having the issue. I tried your code in Anaconda/Spyder, Python 2.7. The plots appear with Bold labels (A,B,C,D). I agree the issue is probably with the library. Try replacing / updating font_manager.py or confirming font files are present:
Lib\site-packages\matplotlib\mpl-data\fonts\ttf\
I had the same problem and spent quite a few hours today on that. Here`s the solution that helped me:
import matplotlib
matplotlib.font_manager._rebuild()
With this, the font_manager could be upgraded easily.
Related
Consider the following code:
import seaborn as sb
import matplotlib.pyplot as plt
import numpy as np
def main():
dst = np.ones((100,100),dtype=np.float32)
ax = plt.subplots(figsize=(17, 17))
sb.heatmap(dst, linewidths=.5, vmax=np.max(dst), vmin=np.min(dst), square=True, cmap="RdYlBu_r", cbar=False).get_figure().savefig("sb_save.png")
plt.show()
if __name__ == "__main__": main()
Now the saved plot looks like this,
which is clearly irregular; on the other hand, this is the output of plt.show(),
which although on a closer look you would still be able to recognize the uneven size of its square cells, it's overall acceptable.
The behavior might have been triggered because of the particulars of invoking savefig but I don't know of an alternative to try here. Any help would be much appreciated.
When I plot an image, my Navigation toolbar (zoom-in, forward, back...) is invisible. I helped myself with this link: disable matplotlib toolbar. I have first tried:
import matplotlib as mpl
mpl.rcParams['toolbar'] = 'toolbar2'
And also checked if in the file itself is set as 'None' but it is not.
Did I perhaps forget to install some packages? Even though I don't get any errors.
Is there alternative way to zoom-in and see the coordinates of cursor, because that is all I need.
Edit 1
This is the code which I am using. I copied just the part, where I use plot.
#___plotting part___
import matplotlib as mpl
mpl.rcParams['toolbar'] = 'toolbar2'
import matplotlib.pyplot as plt
plt.ion()
fig, ax = plt.subplots(figsize=(20, 10))
ax.set_title(plot_titel, loc='center', fontname=font_name, fontsize=16, color='black')
ax.set_xlabel('Column number', fontname=font_name, fontsize=16, color='black')
ax.set_ylabel('Mean of raw backscatter', fontname=font_name, fontsize=16, color='black')
ax.plot(range(len(param_image)), param_image, c='black', marker='o')
ax.plot(idx1[0], param_image[idx1], c='red', mec='red', marker='o', linestyle='')
ax.plot(idx2, param_image[idx2], c='blue', mec='blue', marker='o', linestyle='')
ax.grid()
fig.tight_layout()
plt.show()
I had the same problem before. uninstall it and then install it again (try to use Anaconda or miniconda distribution to install). for sure after that it will work.
do not mess with matplotlibrc
I tried to find the answer for my question for some time now but could not come up with something that works for me. My question is: How can you use Xelatex to compile text in Matplotlib?
I know that there is this page:
http://matplotlib.org/users/pgf.html
However, I could not come up with something that would work. What I got up to now:
import matplotlib as mpl
mpl.use("pgf")
## TeX preamble
preamble = """
\usepackage{fontspec}
\setmainfont{Linux Libertine O}
"""
params = {"text.usetex": True,
'pgf.texsystem': 'xelatex',
'pgf.preamble': preamble}
mpl.rcParams.update(params)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.xlabel(r'\textsc{Something in small caps}', fontsize=20)
plt.ylabel(r'Normal text ...', fontsize=20)
plt.savefig('test.pdf')
Running this code produces the following warning:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_pgf.py:51: UserWarning: error getting fonts from fc-list
warnings.warn('error getting fonts from fc-list', UserWarning)
An output file is created but I don't the font is wrong (not Linux Libertine), even though I have the font installed and am able to use it with XeLaTex (I am able to write a pdf file using xelatex that is set in the Linux Libertine font).
Any help would be really appreciated....
There are a few problems with your code:
You need to give latex the control over the fonts by using the option:
'pgf.rcfonts': False
You should also use unicode for xelatex: 'text.latex.unicode': True.
'pgf.preamble' expects a python lists of single latex commands.
if you set the font to 'Linux Libertine O' you probably want serif fonts,
so 'font.family': 'serif'
beware of escape sequences in the preamble, you should make it raw strings
add a unicode tag at the beginning of the file and be sure the encoding is utf-8
Using this, your code becomes:
# -*- coding:utf-8 -*-
import matplotlib as mpl
mpl.use("pgf")
## TeX preamble
preamble = [
r'\usepackage{fontspec}',
r'\setmainfont{Linux Libertine O}',
]
params = {
'font.family': 'serif',
'text.usetex': True,
'text.latex.unicode': True,
'pgf.rcfonts': False,
'pgf.texsystem': 'xelatex',
'pgf.preamble': preamble,
}
mpl.rcParams.update(params)
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.xlabel(r'\textsc{Something in small caps}', fontsize=20)
plt.ylabel(r'Normal text ...', fontsize=20)
plt.savefig('test.pdf')
Result:
I installed Netbeans and Python IDE 2.7.1 as instructed in the standard installation guide. I would like to run the following code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = Axes3D(fig)
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)
ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
After running the code, I am getting the following error message:
ImportError: No module named mpl_toolkits.mplot3d
Also, for almost all programs I have tested, I get the same import error message.
Could someone assist?
With this description it seems that you have an installation problem at hand. Questions:
can you import matplotlib at all (you may, e.g., try to import matplotlib and see if that throws an error)
if you can import matplotlib, what does matplotlib.__version__ say?
which OS, which python (import sys; print sys.version)
First guess is that you do not have matplotlib installed in a way your interpreter would find it.
Code
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
ax.set_ylim(-2,2)
plt.show()
from http://matplotlib.org/1.2.0/users/annotations_intro.html
return
TypeError: 'dict' object is not callable
I manged to fixed it with
xxx={'facecolor':'black', 'shrink':0.05}
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=xxx,
)
Is this the best way ?
Also what caused this problem ? ( I know that this started with Python 2.7)
So if somebody know more, please share.
Since the code looks fine and runs ok on my machine, it seems that you may have a variable named "dict" (see this answer for reference). A couple of ideas on how to check:
use Pylint.
if you suspect one specific builtin, try checking it's type (type(dict)), or look at the properties/functions it has (dir(dict)).
open a fresh notebook and try again, if you only observe the problem in interactive session.
try alternate syntax to initialise the dictionary
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops={'facecolor':'black', 'shrink':0.05})
try explicitly instancing a variable of this type, using the alternate syntax (as you did already).