matplotlib: how to hide grey border around the plot - matplotlib

I'd like to save figurecanvas as bitmap and don't need grey border around the plot in it. How can I hide this?

I believe that savefig will not include the gray border by default. However, .bmp is not support by savefig; use .png instead.
import pylab
f = pylab.figure()
ax = f.add_axes([0.1, 0.1, 0.8, 0.8])
ax.plot([1,2,3],[4,5,6])
f.savefig('image.png')
Output:
(source: stevetjoa.com)

I found it: subplots_adjust.

Related

Make a label both Italic and Bold style in Matplotlib with stix font

I am trying to generate a plot with matplotlib and I use the 'stix' font (rcParams['mathtext.fontset'] = 'stix') in order to have smooth font size transitions from text to math text. However, some of my math symbols I want to be Italic (scalar values) and some to be Italic AND Bold (tensors). I do not want to go through the solution of using Latex rendering cause then other things are messed up.
I will give you a small example that depicts the problem:
from numpy import *
from matplotlib.pyplot import *
# Chaning font to stix
rcParams['mathtext.fontset'] = 'stix'
# Some data to constract this plotting example
datax=[0,1,2]
datay=[8,9,10]
datay2=[8,15,10]
fig, ay = subplots()
ay.plot(datax, datay, color="0.", ls='-', label= r"$F_{\alpha}$")
ay.plot(datax, datay2, color="0.", ls='-', label=r"$\mathbf{F_{\alpha}}$")
# Now add the legend with some customizations.
legend = ay.legend(loc='left', shadow=True)
#frame = legend.get_frame()
#frame.set_facecolor('0.90')
xlabel(r"x label",fontsize=18)
ylabel(r'y label', fontsize=18)
grid()
show()
If you run the code the first label is Italic and the second label is Bold. How could I achieve the second label to be Bold AND Italic?
Problem with math text to be Italic and bold
A few more specific mathtext params are needed:
from numpy import *
from matplotlib.pyplot import *
# Changing font to stix; setting specialized math font properties as directly as possible
rcParams['mathtext.fontset'] = 'custom'
rcParams['mathtext.it'] = 'STIXGeneral:italic'
rcParams['mathtext.bf'] = 'STIXGeneral:italic:bold'
# Some data to construct this plotting example
datax=[0,1,2]
datay=[8,9,10]
datay2=[8,15,10]
fig, ay = subplots()
ay.plot(datax, datay, color="0.", ls='-', label= r"$\mathit{F_{\alpha}}$")
ay.plot(datax, datay2, color="0.", ls='-', label=r"$\mathbf{F_{\alpha}}$")
# Now add the legend with some customizations.
legend = ay.legend(loc='left', shadow=True)
# Using the specialized math font again
xlabel(r"$\mathbf{x}$ label",fontsize=18)
ylabel(r'y label', fontsize=18)
grid()
show()
Note that I used the mathbf in an axis label, too. Would probably change the rest of the label to a STIX font, which you can define a non-italic-non-bold case of: see the docs under 'Custom fonts'.
There are also at least two examples in the matplotlib Gallery that might help: one looking at font families and another reminding us which STIX fonts are which.
So MatplotLib is using LaTeX syntax, so my best guess is that you can use LaTeX syntax for how to get italicized and bold, which is
\textbf{\textit{text}}
So in your case it would be
ay.plot(datax, datay2, color="0.", ls='-', label= r"$\mathbf{ \textit{F_{\alpha}} }$")

hatched rectangle patches without edges in matplotlib

When trying to add a rectangle patch with a hatch pattern to a plot it seems that it is impossible to set the keyword argument edgecolor to 'none' when also specifying a hatch value.
In other words I am trying to add a hatched rectangle WITHOUT an edge but WITH a pattern filling. This doesnt seem to work. The pattern only shows up if I also allow an edge to be drawn around the rectangle patch.
Any help on how to achieve the desired behaviour?
You should use the linewidth argument, which has to be set to zero.
Example (based on your other question's answer):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
# generate some data:
x,y = np.meshgrid(np.linspace(0,1),np.linspace(0,1))
z = np.ma.masked_array(x**2-y**2,mask=y>-x+1)
# plot your masked array
ax.contourf(z)
# plot a patch
p = patches.Rectangle((20,20), 20, 20, linewidth=0, fill=None, hatch='///')
ax.add_patch(p)
plt.show()
You'll get this image:

Matplotlib, Consistent font using latex

My problem is I'd like to use Latex titles in some plots, and no latex in others. Right now, matplotlib has two different default fonts for Latex titles and non-Latex titles and I'd like the two to be consistent. Is there an RC setting I have to change that will allow this automatically?
I generate a plot with the following code:
import numpy as np
from matplotlib import pyplot as plt
tmpData = np.random.random( 300 )
##Create a plot with a tex title
ax = plt.subplot(211)
plt.plot(np.arange(300), tmpData)
plt.title(r'$W_y(\tau, j=3)$')
plt.setp(ax.get_xticklabels(), visible = False)
##Create another plot without a tex title
plt.subplot(212)
plt.plot(np.arange(300), tmpData )
plt.title(r'Some random numbers')
plt.show()
Here is the inconsistency I am talking about. The axis tick labels are thin looking relative to the titles.:
To make the tex-style/mathtext text look like the regular text, you need to set the mathtext font to Bitstream Vera Sans,
import matplotlib
matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Bitstream Vera Sans'
matplotlib.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic'
matplotlib.rcParams['mathtext.bf'] = 'Bitstream Vera Sans:bold'
matplotlib.pyplot.title(r'ABC123 vs $\mathrm{ABC123}^{123}$')
If you want the regular text to look like the mathtext text, you can change everything to Stix. This will affect labels, titles, ticks, etc.
import matplotlib
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
matplotlib.pyplot.title(r'ABC123 vs $\mathrm{ABC123}^{123}$')
Basic idea is that you need to set both the regular and mathtext fonts to be the same, and the method of doing so is a bit obscure. You can see a list of the custom fonts,
sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
As others mentioned, you can also have Latex render everything for you with one font by setting text.usetex in the rcParams, but that's slow and not entirely necessary.
EDIT
if you want to change the fonts used by LaTeX inside matplotlib, check out this page
http://matplotlib.sourceforge.net/users/usetex.html
one of the examples there is
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
Just pick your favorite!
And if you want a bold font, you can try \mathbf
plt.title(r'$\mathbf{W_y(\tau, j=3)}$')
EDIT 2
The following will make bold font default for you
font = {'family' : 'monospace',
'weight' : 'bold',
'size' : 22}
rc('font', **font)

Adding a grid on top of a tif image in python

Hi I was wondering how to add a grid on top of my image then display it in python.
Here is a picture of what I want to do. NOTE: I also want to specify the line type and color for some of the blocks in the image just like the image below.
Thanks a lot.
The example below shows how to display a .tif file, create a grid, but also how to put the grid below the other plot elements so that you can draw boxes and lines on top of the image and the grid.
import matplotlib.pyplot as plt
from PIL import Image
import matplotlib.patches as mpatches
im = Image.open('stinkbug.tif')
# Flip the .tif file so it plots upright
im1 = im.transpose(Image.FLIP_TOP_BOTTOM)
# Plot the image
plt.imshow(im1)
ax = plt.gca()
# create a grid
ax.grid(True, color='r', linestyle='--', linewidth=2)
# put the grid below other plot elements
ax.set_axisbelow(True)
# Draw a box
xy = 200, 200,
width, height = 100, 100
ax.add_patch(mpatches.Rectangle(xy, width, height, facecolor="none",
edgecolor="blue", linewidth=2))
plt.draw()
plt.show()
You can use matplotlib.patches to draw all types of shapes over your image. To draw individual lines, I like to use the following line, but you can also use matplotlib.lines.Line2D.
plt.axvline(x=0.069, ymin=0, ymax=40, linewidth=4, color='r')
There's imshow function for displaying the image. Displaying the grid on top of the axes is as simple as grid(True).

matplotlib: Controlling pie chart font color, line width

I'm using some simple matplotlib functions to draw a pie chart:
f = figure(...)
pie(fracs, explode=explode, ...)
However, I couldn't find out how to set a default font color, line color, font size – or pass them to pie(). How is it done?
Showing up a bit late for the party but I encountered this problem and didn't want to alter my rcParams.
You can resize the text for labels or auto-percents by keeping the text returned from creating your pie chart and modifying them appropriately using matplotlib.font_manager.
You can read more about using the matplotlib.font_manager here:
http://matplotlib.sourceforge.net/api/font_manager_api.html
Built in font sizes are listed in the api;
"size: Either an relative value of ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’ or an absolute font size, e.g. 12"
from matplotlib import pyplot as plt
from matplotlib import font_manager as fm
fig = plt.figure(1, figsize=(6,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
plt.title('Raining Hogs and Dogs')
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
patches, texts, autotexts = ax.pie(fracs, labels=labels, autopct='%1.1f%%')
proptease = fm.FontProperties()
proptease.set_size('xx-small')
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)
plt.show()
Global default colors, line widths, sizes etc, can be adjusted with the rcParams dictionary:
import matplotlib
matplotlib.rcParams['text.color'] = 'r'
matplotlib.rcParams['lines.linewidth'] = 2
A complete list of params can be found here.
You could also adjust the line width after you draw your pie chart:
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(8,8))
pieWedgesCollection = plt.pie([10,20,50,20],labels=("one","two","three","four"),colors=("b","g","r","y"))[0] #returns a list of matplotlib.patches.Wedge objects
pieWedgesCollection[0].set_lw(4) #adjust the line width of the first one.
Unfortunately, I can not figure out a way to adjust the font color or size of the pie chart labels from the pie method or the Wedge object. Looking in the source of axes.py (lines 4606 on matplotlib 99.1) they are created using the Axes.text method. This method can take a color and size argument but this is not currently used. Without editing the source, your only option may be to do it globally as described above.
matplotlib.rcParams['font.size'] = 24
does change the pie chart labels font size