All,
Attached, and below, is public domain code for making variable-sized
plots with autoscaled text that exactly fits the available visual plot
space, useful for web sites where users choose output files with different
sizes. Examples are at the bottom of the file.
James R. Phillips
2548 Vera Cruz Drive
Birmingham, AL 35235 USA
email: zun...@zunzun.com
http://zunzun.com
#Entered into the public domain 20 March 2009
#James R. Phillips
#2548 Vera Cruz Drive
#Birmingham, AL 35235 USA
#email: zun...@zunzun.com
#http://zunzun.com
import numpy as np
import math, matplotlib
matplotlib.use('Agg') # must be used prior to the next two statements
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
def DetermineOnOrOffFromString(in_String):
tempString = in_String.split('_')[-1:][0].upper() # allows any amount of
prefacing text
if tempString == 'ON':
return True
return False
def DetermineScientificNotationFromString(inData, in_String):
tempString = in_String.split('_')[-1:][0].upper() # allows any amount of
prefacing text
if tempString == 'ON':
return True
elif tempString == 'OFF':
return False
else: # must be AUTO
minVal = np.abs(np.min(inData))
maxVal = np.abs(np.max(inData))
deltaVal = np.abs(maxVal - minVal)
scientificNotation = False
if (maxVal 100.0) or (minVal -100.0) or (deltaVal .05):
scientificNotation = True
return scientificNotation
def CommonPlottingCode(in_WidthInPixels, in_HeightInPixels, in_XName,
in_YName, in_UseOffsetIfNeeded, in_X_UseScientificNotationIfNeeded,
in_Y_UseScientificNotationIfNeeded, in_Left, in_Bottom, in_Right, in_Top): #
default to lots of room around graph
# a litle more room between x axis and tick mark labels, so not text
overlap at the bottom left corner - set this before other calls
matplotlib.rcParams['xtick.major.pad'] = 5+ (float(in_HeightInPixels) /
100.0) # minimum + some scaled
fig = plt.figure(figsize=(float(in_WidthInPixels ) / 100.0,
float(in_HeightInPixels ) / 100.0), dpi=100)
fig.subplotpars.update(in_Left, in_Bottom, in_Right, in_Top)
ax = fig.add_subplot(111, frameon=True)
# white background, almost no border space
fig.set_facecolor('w')
xFormatter = fig.gca().xaxis.get_major_formatter()
xFormatter._useOffset = in_UseOffsetIfNeeded
xFormatter.set_scientific(in_X_UseScientificNotationIfNeeded)
fig.gca().xaxis.set_major_formatter(xFormatter)
yFormatter = fig.gca().yaxis.get_major_formatter()
yFormatter._useOffset = in_UseOffsetIfNeeded
yFormatter.set_scientific(in_Y_UseScientificNotationIfNeeded)
fig.gca().yaxis.set_major_formatter(yFormatter)
# Scale text to imagesize. Text sizes originally determined at image
size of 500 x 400
widthRatioForTextSize = float(in_WidthInPixels) / 500.0
heightRatioForTextSize = float(in_HeightInPixels) / 400.0
for xlabel_i in ax.get_xticklabels():
xlabel_i.set_fontsize(xlabel_i.get_fontsize() *
heightRatioForTextSize)
xOffsetText = fig.gca().xaxis.get_offset_text()
xOffsetText.set_fontsize(xOffsetText.get_fontsize() *
heightRatioForTextSize * 0.9)
for ylabel_i in ax.get_yticklabels():
ylabel_i.set_fontsize(ylabel_i.get_fontsize() *
widthRatioForTextSize)
yOffsetText = fig.gca().yaxis.get_offset_text()
yOffsetText.set_fontsize(yOffsetText.get_fontsize() *
heightRatioForTextSize * 0.9)
x_label = ax.set_xlabel(in_XName)
y_label = ax.set_ylabel(in_YName)
x_label._fontproperties._size = x_label._fontproperties._size *
heightRatioForTextSize
y_label._fontproperties._size = y_label._fontproperties._size *
widthRatioForTextSize
plt.grid(True) # call this just before returning
return fig, ax
def YieldNewExtentsAndNumberOfMajor_X_TickMarks(fig, ax, in_WidthInPixels,
in_HeightInPixels, in_OffsetUsed):
# draw everything so items can be measured for size
canvas = plt.get_current_fig_manager().canvas
canvas.draw()
# some preliminary info
xLabelPoints =
ax.set_xlabel(ax.get_xlabel()).get_window_extent().get_points() # [ [x,y],
[x,y] ]
yLabelPoints =
ax.set_ylabel(ax.get_ylabel()).get_window_extent().get_points() # [ [x,y],
[x,y] ], rotated 90 degrees
xTickZeroPoints =
ax.get_xticklabels()[0].get_window_extent().get_points()
yTickZeroPoints =
ax.get_yticklabels()[0].get_window_extent().get_points()
xTickIndexPoints =
ax.get_xticklabels()[len(ax.get_xticklabels())-1].get_window_extent().get_points()
yTickIndexPoints =
ax.get_yticklabels()[len(ax.get_yticklabels())-1].get_window_extent().get_points()
currentPoints = ax.bbox.get_points()
maxLeft = currentPoints[0][0]
maxBottom = currentPoints[0][1]
maxRight = currentPoints[1][0]
maxTop = currentPoints[1][1]
# find the most left-ward location
if xTickZeroPoints[0][0] maxLeft: