本文整理汇总了Python中matplotlib.pyplot.rcdefaults函数的典型用法代码示例。如果您正苦于以下问题:Python rcdefaults函数的具体用法?Python rcdefaults怎么用?Python rcdefaults使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了rcdefaults函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: show_sensfunc
def show_sensfunc(self):
"""
Plot the sensitivity function
"""
if self.sens_dict is None:
msgs.warn("You need to generate the sensfunc first!")
return None
plt.rcdefaults()
plt.rcParams["xtick.top"] = True
plt.rcParams["ytick.right"] = True
plt.rcParams["xtick.minor.visible"] = True
plt.rcParams["ytick.minor.visible"] = True
plt.rcParams["ytick.direction"] = 'in'
plt.rcParams["xtick.direction"] = 'in'
plt.rcParams["xtick.labelsize"] = 13
plt.rcParams["ytick.labelsize"] = 13
plt.rcParams['font.family'] = 'times new roman'
norder = self.sens_dict['norder']
for iord in range(norder):
sens_dict_iord = self.sens_dict[str(iord)]
plt.plot(sens_dict_iord['wave'], sens_dict_iord['sensfunc'])
plt.xlabel('Wavelength [ang]', fontsize=14)
plt.ylabel('Sensfunc', fontsize=14)
plt.ylim([0., 100.0])
plt.show()
开发者ID:PYPIT,项目名称:PYPIT-development-suite,代码行数:25,代码来源:ech_fluxspec_class.py
示例2: setup_location
def setup_location(station_type):
data = testing.getTestROSData()
np.random.seed(0)
loc = Location(data, station_type=station_type, bsIter=10000,
rescol='res', qualcol='qual', useROS=True)
plt.rcdefaults()
return loc
开发者ID:SeanMcKnight,项目名称:wqio,代码行数:7,代码来源:features_tests.py
示例3: plot_clusterings
def plot_clusterings(target, source, env):
"""
Plot items with clustering from first file, using 2-d coordinates from second file.
The functions GET_COORDS and GET_CLUSTS specify operations to turn each file object
into a mapping from item name to coordinate tuple or cluster number, respectively.
"""
pyplot.rcdefaults()
pyplot.figure(figsize=(10, 10))
args = source[-1].read()
# rcdefaults()
clusts = dict(ri2py(eval("lambda x : %s" % args.get("GET_CLUSTERS", "x"))(numpy.load(source[0].rstr()))).rx2("cluster").iteritems())
coords = eval("lambda x : %s" % args.get("GET_COORDS", "x"))(numpy.load(source[1].rstr()))
labels = coords.keys()
#if args.get("NORMALIZE", False):
# for i in [0, 1]:
# ttcoords[:, i] = (ttcoords[:, i] - ttcoords[:, i].min()) / numpy.max(ttcoords[:, i] - ttcoords[:, i].min())
[pyplot.scatter(coords[l][0], coords[l][1], label=l, s=64, marker=shapes[clusts[l]], color=colors[clusts[l]]) for i, l in enumerate(labels)]
ymin, ymax = pyplot.ylim()
inc = (ymax - ymin) / 40.0
[pyplot.text(coords[l][0], coords[l][1] + inc, l, fontsize=12, ha="center") for i, l in enumerate(labels)]
pyplot.xticks([], [])
pyplot.yticks([], [])
pyplot.xlabel("First principal component")
pyplot.ylabel("Second principal component")
pyplot.savefig(target[0].rstr(), bbox_inches="tight")
pyplot.cla()
return None
开发者ID:TomLippincott,项目名称:python,代码行数:30,代码来源:plotting_tools.py
示例4: plot
def plot():
#Read in the airmass terms and the MJDs
data = ascii.read('airmass.dat')
mjds, airmasses, sites = data['mjd'], data['airmass'], data['site']
setup_plot()
colors = {'lsc':'blue', 'cpt':'red', 'coj': 'green'}
for site in ['lsc', 'cpt', 'coj']:
where_site = sites == site
pyplot.plot(mjds[where_site] - 57000, airmasses[where_site],
'o', color=colors[site])
pyplot.xlim(7.7, 10.3)
pyplot.ylim(2.35, 0.95)
pyplot.xlabel('MJD - 57000')
pyplot.ylabel('Airmass')
a = pyplot.annotate("", xy=(8.75, 1.2), xycoords='data',xytext=(8.30, 1.2), textcoords='data',
arrowprops={'arrowstyle':"<->"})
a.arrow_patch.set_linewidth(2)
pyplot.text(8.525, 1.17,'Bad Weather', ha='center', fontsize='medium')
pyplot.legend(labels=['Chile', 'South Africa', 'Australia'], loc=3)
pyplot.savefig('he0435_airmass.pdf', bbox_inches='tight', pad_inches=0.05)
pyplot.show()
pyplot.rcdefaults()
开发者ID:cmccully,项目名称:he0435,代码行数:27,代码来源:plot_airmass.py
示例5: graph_FWHM_data_range
def graph_FWHM_data_range(start_date=datetime.datetime(2015,3,6),
end_date=datetime.datetime(2015,4,15),tenmin=True,
path='/home/douglas/Dropbox (Thacher)/Observatory/Seeing/Data/',
write=True,outpath='./'):
plot_params()
fwhm = get_FWHM_data_range(start_date = start_date, end_date=end_date, path=path, tenmin=tenmin)
# Basic stats
med = np.median(fwhm)
mean = np.mean(fwhm)
fwhm_clip, low, high = sigmaclip(fwhm,low=3,high=3)
meanclip = np.mean(fwhm_clip)
# Get mode using kernel density estimation (KDE)
vals = np.linspace(0,30,1000)
fkde = gaussian_kde(fwhm)
fpdf = fkde(vals)
mode = vals[np.argmax(fpdf)]
std = np.std(fwhm)
plt.ion()
plt.figure(99)
plt.clf()
plt.hist(fwhm, color='darkgoldenrod',bins=35)
plt.xlabel('FWHM (arcsec)',fontsize=16)
plt.ylabel('Frequency',fontsize=16)
plt.annotate('mode $=$ %.2f" ' % mode, [0.87,0.85],horizontalalignment='right',
xycoords='figure fraction',fontsize='large')
plt.annotate('median $=$ %.2f" ' % med, [0.87,0.8],horizontalalignment='right',
xycoords='figure fraction',fontsize='large')
plt.annotate('mean $=$ %.2f" ' % mean, [0.87,0.75],horizontalalignment='right',
xycoords='figure fraction',fontsize='large')
xvals = np.linspace(0,30,1000)
kde = gaussian_kde(fwhm)
pdf = kde(xvals)
dist_c = np.cumsum(pdf)/np.sum(pdf)
func = interp1d(dist_c,vals,kind='linear')
lo = np.float(func(math.erfc(1./np.sqrt(2))))
hi = np.float(func(math.erf(1./np.sqrt(2))))
disthi = np.linspace(.684,.999,100)
distlo = disthi-0.6827
disthis = func(disthi)
distlos = func(distlo)
interval = np.min(disthis-distlos)
plt.annotate('1 $\sigma$ int. $=$ %.2f" ' % interval, [0.87,0.70],horizontalalignment='right',
xycoords='figure fraction',fontsize='large')
plt.rcdefaults()
plt.savefig(outpath+'Seeing_Cumulative.png',dpi=300)
return
开发者ID:ThacherObservatory,项目名称:observatory,代码行数:60,代码来源:seeing.py
示例6: test_basic_matplotlib
def test_basic_matplotlib():
"""
Based on the demo at: http://matplotlib.org/examples/lines_bars_and_markers/barh_demo.html
Viewed on 4 August 2014
Simple demo of a horizontal bar chart.
"""
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, people)
plt.xlabel('Performance')
plt.title('How fast do you want to go today?')
text = wordgraph.describe(plt, source='matplotlib')
assert text is not None
开发者ID:kcunning,项目名称:wordgraph,代码行数:25,代码来源:test_matplotlib.py
示例7: __init__
def __init__(self):
threading.Thread.__init__(self)
self.setDaemon(True)
self._homeDir = os.path.expanduser("~/.sensomatic")
self._configFileName = self._homeDir + '/config.ini'
self._config = ConfigParser.ConfigParser()
self._readConfig()
plt.rcdefaults()
开发者ID:AnsgarSchmidt,项目名称:sensomatic,代码行数:8,代码来源:Statisticer.py
示例8: mplSetupStandard
def mplSetupStandard():
mpl.rcdefaults()
mpl.rc('figure',
dpi = 100,
figsize = (6,6),
facecolor = 'white',
autolayout = True
)
开发者ID:jhugon,项目名称:astroobsplanner,代码行数:8,代码来源:mplsetup.py
示例9: process_blocks
def process_blocks(blocks, src_path, image_path, cfg):
"""Run source, save plots as images, and convert blocks to rst.
Parameters
----------
blocks : list of block tuples
Code and text blocks from example. See `split_code_and_text_blocks`.
src_path : str
Path to example file.
image_path : str
Path where plots are saved (format string which accepts figure number).
cfg : config object
Sphinx config object created by Sphinx.
Returns
-------
figure_list : list
List of figure names saved by the example.
rst_text : str
Text with code wrapped code-block directives.
"""
src_dir, src_name = src_path.psplit()
if not src_name.startswith('plot'):
convert_func = dict(code=codestr2rst, text=docstr2rst)
rst_blocks = [convert_func[blabel](bcontent)
for i, (blabel, brange, bcontent) in enumerate(blocks)]
return [], '\n'.join(rst_blocks)
# index of blocks which have inline plots
inline_tag = cfg.plot2rst_plot_tag
idx_inline_plot = [i for i, b in enumerate(blocks)
if inline_tag in b[2]]
image_dir, image_fmt_str = image_path.psplit()
figure_list = []
plt.rcdefaults()
plt.rcParams.update(cfg.plot2rst_rcparams)
plt.close('all')
example_globals = {}
rst_blocks = []
fig_num = 1
for i, (blabel, brange, bcontent) in enumerate(blocks):
if blabel == 'code':
exec(bcontent, example_globals)
rst_blocks.append(codestr2rst(bcontent))
else:
if i in idx_inline_plot:
plt.savefig(image_path.format(fig_num))
figure_name = image_fmt_str.format(fig_num)
fig_num += 1
figure_list.append(figure_name)
figure_link = os.path.join('images', figure_name)
bcontent = bcontent.replace(inline_tag, figure_link)
rst_blocks.append(docstr2rst(bcontent))
return figure_list, '\n'.join(rst_blocks)
开发者ID:gcalmettes,项目名称:mpltools,代码行数:57,代码来源:plot2rst.py
示例10: clear
def clear(self):
"""Custom clear method that resets everything back o defaults."""
attrs = [x for x in dir(self) if self._allowed_attr(x)]
defaults = self.__class__()
for attr in attrs:
setattr(self, attr, getattr(defaults, attr))
plt.rcdefaults()
attrs = [x for x in dir(self) if self._allowed_attr(x, template=True)]
for attr in attrs:
delattr(self, attr)
开发者ID:gb119,项目名称:Stoner-PythonCode,代码行数:10,代码来源:formats.py
示例11: plot_nstars
def plot_nstars(cat_ra, cat_mjd, suff):
nstars = [max([len(frame) for frame in ra]) for ra in cat_ra]
mjd = [np.average(mjd) for mjd in cat_mjd]
plt.rcdefaults()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(mjd, nstars, '.')
ax.set_xlabel('MJD')
ax.set_ylabel('Maximum number of stars per night')
fig.savefig(param['output_path']+'maximum_number_of_stars_per_night'+suff, bbox_inches='tight', pad_inches=0.05)
plt.close(fig)
开发者ID:xparedesfortuny,项目名称:Phot,代码行数:11,代码来源:quality_control.py
示例12: plot_temps
def plot_temps():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100, 0.1)
gauss1 = gauss(x, 5, 50, 1)
gauss2 = gauss(x, 10, 50, 1)
gauss3 = gauss(x, 15, 50, 1)
gauss1 /= np.sum(gauss1)
gauss2 /= np.sum(gauss2)
gauss3 /= np.sum(gauss3)
scale = np.max(np.array((gauss1, gauss2, gauss3)))
gauss1 /= scale
gauss2 /= scale
gauss3 /= scale
# Set up plot aesthetics
plt.clf()
plt.close()
plt.rcdefaults()
colormap = plt.cm.gist_ncar
font_scale = 20
params = {#'backend': .pdf',
'axes.labelsize': font_scale,
'axes.titlesize': font_scale,
'text.fontsize': font_scale,
'legend.fontsize': font_scale * 4.0 / 4.0,
'xtick.labelsize': font_scale,
'ytick.labelsize': font_scale,
'font.weight': 500,
'axes.labelweight': 500,
'text.usetex': False,
#'figure.figsize': (8, 8 * y_scaling),
#'axes.color_cycle': color_cycle # colors of different plots
}
plt.rcParams.update(params)
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
ax.plot(x, gauss1, label='Cold', linewidth=3)
ax.plot(x, gauss2, label='Warm', linewidth=3)
ax.plot(x, gauss3, label='Hot', linewidth=3)
ax.set_xlabel('Velocity (km/s)')
ax.set_ylabel('Intensity')
ax.legend()
plt.savefig('gauss_temps.png')
开发者ID:ezbc,项目名称:class_work,代码行数:54,代码来源:plots_script.py
示例13: setup_jointplot
def setup_jointplot():
plt.rcdefaults()
np.random.seed(0)
N = 37
df = pandas.DataFrame({
'A': np.random.normal(size=N),
'B': np.random.lognormal(mean=0.25, sigma=1.25, size=N),
'C': np.random.lognormal(mean=1.25, sigma=0.75, size=N)
})
return df
开发者ID:SeanMcKnight,项目名称:wqio,代码行数:11,代码来源:figutils_tests.py
示例14: plot_derivs
def plot_derivs():
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100, 0.1)
params = (x, 15, 50, 1)
gauss1 = gauss(*params)
gauss1d = gauss_1st_deriv(*params)
gauss2d = gauss_2nd_deriv(*params)
gauss3d = gauss_3rd_deriv(*params)
gauss4d = gauss_4th_deriv(*params)
deriv_list = [gauss1d, gauss2d, gauss3d, gauss4d,]
for i, comp in enumerate(deriv_list):
deriv_list[i] = comp / np.max(comp)
# Set up plot aesthetics
plt.clf()
plt.close()
plt.rcdefaults()
colormap = plt.cm.gist_ncar
font_scale = 15
params = {#'backend': .pdf',
'axes.labelsize': font_scale,
'axes.titlesize': font_scale,
'text.fontsize': font_scale,
'legend.fontsize': font_scale * 4.0 / 4.0,
'xtick.labelsize': font_scale,
'ytick.labelsize': font_scale,
'font.weight': 500,
'axes.labelweight': 500,
'text.usetex': False,
#'figure.figsize': (8, 8 * y_scaling),
#'axes.color_cycle': color_cycle # colors of different plots
}
plt.rcParams.update(params)
fig, ax = plt.subplots(1, 1, figsize=(7, 7))
ax.plot(x, gauss1, linewidth=3, color='k')
ax.set_ylim(-2.5, 1.1)
ax.set_xlabel('Velocity (km/s)')
ax.set_ylabel('Intensity')
plt.savefig('gauss_deriv0.png')
for i, deriv in enumerate(deriv_list):
ax.plot(x, deriv, linewidth=1)
plt.savefig('gauss_deriv' + str(i+1) + '.png')
开发者ID:ezbc,项目名称:class_work,代码行数:54,代码来源:plots_script.py
示例15: MakeSubplots
def MakeSubplots(distances, plot_gender='male', special=False):
pyplot.rc('figure', figsize=(5, 10))
pyplot.rc('font', size=9.0)
pyplot.rc('xtick.major', size=0)
pyplot.rc('ytick.major', size=0)
pyplot.subplots_adjust(wspace=0.4, hspace=0.4,
right=0.95, left=0.15,
top=0.95, bottom=0.05)
t = miles.items()
t.sort(key=lambda x: x[1])
titles = [x[0] for x in t]
gender = plot_gender
i=0
for distance in titles:
i += 1
data = distances[distance, gender]
if gender != plot_gender:
continue
pyplot.subplot(6, 2, i)
if i%2 == 1:
pyplot.ylabel('mph')
xs, ys = zip(*data)
# extend the current record to the present
first_x = xs[1]
last_x = xs[-1]
if special:
pyplot.xticks([1950, 1970, 1990, 2011])
elif i==2:
pyplot.xticks([int(first_x), 2011])
else:
pyplot.xticks([int(first_x), 1960, 2011])
first_y = ys[0]
last_y = ys[-1]
pyplot.plot([last_x, 2012.4], [last_y, last_y], 'b-')
if special:
pyplot.plot([1950, first_x], [first_y, first_y], 'b-')
pyplot.plot(xs, ys, 'o-', markersize=4)
pyplot.title(distance)
root = 'world_record_speed'
myplot.Save(root=root)
pyplot.rcdefaults()
开发者ID:41734785,项目名称:thinkstats,代码行数:54,代码来源:world_record.py
示例16: plot
def plot(self, filename):
# Check that the optical properties have been set
self.optical_properties.ensure_all_set()
import matplotlib.pyplot as plt
# Save original rc parameters
rc_orig = plt.rcParams
# Reset to defaults
plt.rcdefaults()
plt.rc('legend', fontsize=7)
plt.rc('axes', titlesize='x-small')
plt.rc('axes', labelsize='x-small')
plt.rc('xtick', labelsize='xx-small')
plt.rc('ytick', labelsize='xx-small')
plt.rc('axes', linewidth=0.5)
plt.rc('patch', linewidth=0.5)
# Check that emissivities are set (before computing mean opacities)
if not self.emissivities.all_set():
logger.info("Computing emissivities assuming LTE")
self.emissivities.set_lte(self.optical_properties)
# Compute mean opacities if not already existent
if not self.mean_opacities.all_set():
logger.info("Computing mean opacities")
self.mean_opacities.compute(self.emissivities, self.optical_properties)
# Initialize figure
fig = plt.figure(figsize=(10, 12))
# Plot optical properties
fig = self.optical_properties.plot(fig, [421, 423, 424, 425, 426])
# Plot emissivities
fig = self.emissivities.plot(fig, 427)
# Plot mean opacities
fig = self.mean_opacities.plot(fig, 428)
# Adjust spacing between subplots
fig.subplots_adjust(left=0.08, right=0.92, wspace=0.22, hspace=0.30)
# Save figure
fig.savefig(filename, bbox_inches='tight')
# Close figure to save RAM
plt.close(fig)
# Restore rc parameters
plt.rc(rc_orig)
开发者ID:goranka,项目名称:hyperion,代码行数:53,代码来源:dust_type.py
示例17: __delitem__
def __delitem__(self, name):
if hasattr(self, name):
default = getattr(self.__class__(), name)
setattr(self, name, default)
elif name in plt.rcParams:
params = dict(plt.rcParams)
del params[name]
plt.rcdefaults()
plt.rcParams.update(params)
super(DefaultPlotStyle, self).__delattr__(_remove_dots("template_{}".format(name)))
else:
raise KeyError("{} is not recognised as part of the template".format(name))
开发者ID:gb119,项目名称:Stoner-PythonCode,代码行数:12,代码来源:formats.py
示例18: plotLonLat
def plotLonLat(self, lonData, latData, indicator):
"""
Plot the input lat/lon values lagged against themselves,
and the same for the changes in lat/lon.
"""
pyplot.figure(self.figurenum(), figsize=(7, 12))
dlon = lonData[1:] - lonData[:-1]
dlat = latData[1:] - latData[:-1]
j = numpy.where(indicator[1:] == 0)
dlon = dlon[j]
dlat = dlat[j]
# Correct change in longitude where the value jumps across the 180E
# meridian
k = numpy.where(dlon<-180.)
dlon[k] += 360.
pyplot.subplot(211)
pyplot.plot(dlon[1:], dlon[:-1], 'k.', markersize=1)
m, c, r, p, e = _linreg(dlon)
pyplot.text(-3, 3, "r = %5.3f"%r, ha='center',
va='center', color='r', size=14)
pyplot.xlim(-4., 4.)
pyplot.ylim(-4., 4.)
pyplot.xticks(numpy.arange(-4., 4.1, 1.))
pyplot.yticks(numpy.arange(-4., 4.1, 1.))
pyplot.ylabel(r"$\Delta lon (t)$", fontsize=16)
pyplot.xlabel(r"$\Delta lon (t-1)$", fontsize=16)
#pyplot.grid(True)
pyplot.title("Longitude rate of change")
pyplot.subplot(212)
pyplot.plot(dlat[1:], dlat[:-1], 'k.', markersize=1)
m, c, r, p, e = _linreg(dlat)
pyplot.text(-3, 3, "r = %5.3f"%r, ha='center',
va='center', color='r', size=14)
pyplot.xlim(-4., 4.)
pyplot.ylim(-4., 4.)
pyplot.xticks(numpy.arange(-4., 4.1, 1.))
pyplot.yticks(numpy.arange(-4., 4.1, 1.))
pyplot.ylabel(r"$\Delta lat (t)$", fontsize=16)
pyplot.xlabel(r"$\Delta lat (t-1)$", fontsize=16)
pyplot.title("Latitude rate of change")
self.savefig('lonlat_corr')
pyplot.rcdefaults()
self.scatterHistogram(dlon[1:], dlon[:-1], 'dlon_scatterHist')
self.scatterHistogram(dlat[1:], dlat[:-1], 'dlat_scatterHist')
开发者ID:HyeonJeongKim,项目名称:tcrm,代码行数:52,代码来源:plotStats.py
示例19: new_figure
def new_figure(self, figure=False, **kargs):
"""This is called by PlotMixin to setup a new figure before we do anything."""
plt.rcdefaults() # Start by resetting to our default settings
params = dict()
self.apply()
if "fig_width_pt" in dir(self):
self.fig_width = self.fig_width_pt * self._inches_per_pt
if "fig_height_pt" in dir(self):
self.fig_height = self.fig_width * self._golden_mean # height in inches
if "fig_ratio" in dir(self) and "fig_width" in dir(self):
self.fig_height = self.fig_width / self.fig_ratio
if "fig_width" and "fig_height" in self.__dict__:
self.template_figure__figsize = (self.fig_width, self.fig_height)
for attr in dir(self):
if attr.startswith("template_"):
attrname = _add_dots(attr[9:])
value = self.__getattribute__(attr)
if attrname in plt.rcParams.keys():
params[attrname] = value
plt.rcParams.update(params) # Apply these parameters
projection = kargs.pop("projection", "rectilinear")
self.template_figure__figsize = kargs.pop("figsize", self.template_figure__figsize)
if "ax" in kargs: # Giving an axis instance in kargs means we can use that as out figure
ax = kargs.get("ax")
plt.sca(ax)
figure = plt.gcf().number
if isinstance(figure, bool) and not figure:
ret = None
elif figure is not None:
fig = plt.figure(figure, figsize=self.template_figure__figsize)
if len(fig.axes) == 0:
rect = [plt.rcParams["figure.subplot.{}".format(i)] for i in ["left", "bottom", "right", "top"]]
rect[2] = rect[2] - rect[0]
rect[3] = rect[3] - rect[1]
if projection == "3d":
ax = fig.add_subplot(111, projection="3d")
else:
ax = fig.add_axes(rect)
else:
if projection == "3d":
ax = kargs.pop("ax", fig.gca(projection="3d"))
else:
ax = kargs.pop("ax", fig.gca())
ret = fig
else:
if projection == "3d":
ret = plt.figure(figsize=self.template_figure__figsize, **kargs)
ax = ret.add_subplot(111, projection="3d")
else:
ret, ax = plt.subplots(figsize=self.template_figure__figsize, **kargs)
return ret, ax
开发者ID:gb119,项目名称:Stoner-PythonCode,代码行数:52,代码来源:formats.py
示例20: problem_2c
def problem_2c():
import matplotlib.pyplot as plt
m = 1000
a = np.random.uniform(0, 1, size=m)
A = np.matrix([np.ones((m)), a]).T
b = a ** 2 + np.random.normal(0, 1, size=m)
B = np.matrix(b).T
# Fit x
x = np.linalg.inv(A.T * A) * A.T * B
# create b_fit
a_fit = np.arange(0, 1, 0.01)
b_fit = x[0, 0] + x[1, 0] * a_fit ** 2
# Plot!
# Set up plot aesthetics
plt.clf()
plt.rcdefaults()
colormap = plt.cm.gist_ncar
# color_cycle = [colormap(i) for i in np.linspace(0, 0.9, len(flux_list))]
font_scale = 10
params = { #'backend': .pdf',
"axes.labelsize": font_scale,
"axes.titlesize": font_scale,
"text.fontsize": font_scale,
"legend.fontsize": font_scale * 3 / 4.0,
"xtick.labelsize": font_scale,
"ytick.labelsize": font_scale,
"font.weight": 500,
"axes.labelweight": 500,
"text.usetex": False,
#'figure.figsize': (8, 8 * y_scaling),
#'axes.color_cycle': color_cycle # colors of different plots
}
plt.rcParams.update(params)
fig = plt.figure(figsize=(3, 2))
ax = fig.add_subplot(111)
ax.plot(a, b, linestyle="", marker="^", alpha=0.4)
ax.plot(a_fit, b_fit, color="r")
ax.set_xlabel(r"$a_i$")
ax.set_ylabel(r"$b_i$")
plt.savefig("problem2c_fig.png", bbox_inches="tight")
开发者ID:ezbc,项目名称:class_work,代码行数:50,代码来源:hw3.py
注:本文中的matplotlib.pyplot.rcdefaults函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论