本文整理汇总了Python中matplotlib.pyplot.xkcd函数的典型用法代码示例。如果您正苦于以下问题:Python xkcd函数的具体用法?Python xkcd怎么用?Python xkcd使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了xkcd函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_worth_vs_time
def plot_worth_vs_time(self, names=None):
"""Plot the worth of each investor vs. time. If names is specified,
will use these names in the legend. Otherwise, will name the investors
based off their thresholds.
"""
if names is None:
names = [
'Investor ({:0.2f},{:0.2f})'.format(inv.buy_at, inv.sell_at)
for inv in self.investors]
dates = [x[0] for x in self.pe_array]
year = YearLocator()
date_fmt = DateFormatter('%Y')
plt.xkcd()
# investor worth plots
fig = plt.figure()
ax = fig.gca()
lines = []
for i in range(len(self.investors)):
result = ax.plot_date(dates, self.worth_matrix[i], '-')
lines.append(result[0])
ax.xaxis.set_major_locator(year)
ax.xaxis.set_major_formatter(date_fmt)
# ax.xaxis.set_minor_formatter(MonthLocator())
ax.autoscale_view()
ax.legend(lines, names, 'upper left')
fig.autofmt_xdate()
return fig
示例2: makePlot
def makePlot (filename, xkcd, data):
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
x=[m[0] for m in data]
stay = [m[1] for m in data]
spin = [m[2] for m in data]
fig = plt.figure()
if xkcd:
plt.xkcd() # uncomment for xkcd style plots
fig.suptitle("Price is Right Spin Strategy",
fontsize=14, fontweight='bold')
ax = plt.subplot(111) # get default subplot to make it nice
ax.set_ylim(0,100) # force the % to be 0-100
ax.set_xlim(0,100.1) # force a grid line at 100
ax.grid(True) # turn on the grid
ax.spines['top'].set_visible(False) # turn off top part of box (top spine)
ax.spines['right'].set_visible(False) # turn off right part of box (right spine)
ax.yaxis.set_ticks_position('left') # turn off tick marks on right
ax.xaxis.set_ticks_position('none') # turn off tick marks on top and bottom
ax.set_xticks(range(0,110,10)) # set ticks to be by 10s
ax.set_yticks(range(0,110,10)) # set ticks to be by 10s
plt.plot(x,stay,color="b",label="stay")
plt.plot(x,spin,color="r",label="spin again")
plt.fill_between(x,0,stay,alpha=0.2,color='b')
plt.fill_between(x,0,spin,alpha=0.2,color='r')
plt.ylabel("% chance of winning")
plt.xlabel("first spin result")
plt.legend(loc=2) # 2=upper-left (see pydoc matplotlib.pyplot.legend)
fig.savefig(filename, format="png")
示例3: plot_time_series
def plot_time_series(data):
buf = StringIO()
plt.xkcd()
plt.xlabel("Date")
plt.ylabel("Number of events")
axes = plt.axes()
# loc = mdates.AutoDateLocator()
# axes.xaxis.set_major_locator(loc)
# axes.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
max_y = 0
for i, (name, series) in enumerate(data):
series.sort()
series = _group_by_date(series)
# print name, series
times, values = zip(*series)
max_y = max(max_y, max(values))
# times = map(datetime.fromtimestamp, times)
plt.plot(times, values,
label=name,
color=colors[i%len(colors)],
markersize=10.0,
marker=markers[i%len(markers)],
)
# plt.plot_date(x=times, y=values, label=name,
# color=colors[i%len(colors)],
# markersize=10.0,
# marker=markers[i%len(markers)],
# )
plt.ylim(ymin=0, ymax=max_y+10)
xlim = plt.xlim()
plt.xlim(xlim[0]-3, xlim[1]+3)
plt.legend()
plt.savefig(buf, format='png')
plt.close()
return buf.getvalue()
示例4: main
def main():
args = parse_args()
# find top paths by size
toppaths = nlargest_paths(args.csvpath, n=args.number)
# pop the root so we don't graph 100%
root = toppaths[0]
rootpath = root[1]
paths = toppaths[1:]
sizes = np.array([p[0] for p in paths])
names = [p[1][len(rootpath) + 1:] for p in paths]
dumpdata(rootpath, names, sizes)
plt.xkcd()
fig = plt.figure()
ax = fig.gca()
graymap = [mpl.cm.gray(v) for v in np.linspace(0.5,1,len(names))]
plt.pie(sizes, labels=names, colors=graymap)
plt.title('space used\n{}'.format(root))
ax.set_aspect('equal')
plt.show()
示例5: initialize
def initialize(self):
self.figure = matplotlib.figure.Figure(facecolor='white')
self.axes = self.figure.add_subplot(111, xlim=(0,4), ylim=(0, 1), ybound=[0, 1])
plt.xkcd()
self.axes.spines['right'].set_color('none')
self.axes.spines['top'].set_color('none')
self.axes.set_xticks([])
self.axes.set_yticks([])
self.axes.set_ybound(lower=0, upper=1)
probabs = [0.3, 0.3, 0.3]
xlabels = ['R', 'P', 'S']
self.axes.bar([1, 2, 3], probabs, align='center', color='lightskyblue')
for i in range(3):
self.axes.text(i+1, probabs[i] + 0.01, '%.2f' % probabs[i],
ha='center', va='bottom')
self.axes.text(i+1, probabs[i] - 0.05, xlabels[i],
ha='center', va='top')
for i in range(2, 11, 2):
self.axes.text(-0.1, i/10.0, str(i/10.0), ha='right', va='center')
self.axes.set_title('Probability distribution')
self.canvas = FigureCanvas(self, -1, self.figure)
示例6: Make_Plot
def Make_Plot(Apzwn,Afreq):
plt.xkcd()
plt.figure()
tw,nw = Apzwn.shape
for i in range(tw):
plt.plot(Apzwn[i,:],Afreq[i,:], linewidth=1,color='k')
plt.text(3,0.15,'Kelvin', bbox={'facecolor':'white'})
plt.text(-12,0.04,'ER', bbox={'facecolor':'white'})
plt.text(-10,0.15,'MRG', bbox={'facecolor':'white'})
plt.text(3.5,0.37,'IG n=0', bbox={'facecolor':'white'})
plt.text(-2,0.45,'IG n=1', bbox={'facecolor':'white'})
plt.text(-2,0.57,'IG n=2', bbox={'facecolor':'white'})
plt.text(-2,0.68,'IG n=3', bbox={'facecolor':'white'})
plt.plot((0,0), (0,1),'--',linewidth=2,color='k')
plt.text(10,-0.09,'Eastward')
plt.text(-16,-0.09,'Westward')
plt.xlabel('Zonal Wavenumber',size=13,fontweight='bold')
plt.ylabel('Frequency (CPD)',size=13,fontweight='bold')
texto = 'Matsuno Modes'
plt.title(texto,size=15,fontweight='bold')
plt.xlim((-20,20))
plt.ylim((0,1))
plt.savefig('Matsuno.png', format='png')
示例7: frequency_power_plot
def frequency_power_plot(frequency, power, max_x, max_y, save_to):
plt.close()
star_label = 'Highest power: {0}db, corresponding frequency value: {1}hz'.format(int(max_y), int(max_x))
#create subplots ax1 and ax2
plt.xkcd()
f, (ax1, ax2) = plt.subplots(2)
plt.xlabel('Frequency(hz)', color='#4B0082')
plt.ylabel('Power(db)', color='#4B0082')
#plot axis1
ax1.set_title('Frequency-Power plot', color='#4B0082')
ax1.plot(frequency, power, label='Power', color='#FF69B4')
ax1.plot(max_x, max_y, '*', label=star_label, color='#FF7F00')
legend = ax1.legend(loc='lower center', shadow=True, fontsize='x-small')
# legend.get_frame().set_facecolor('#FF69B4')
#plot axis2
ax2.plot(frequency, power, label='Power', color='#FF69B4')
ax2.plot(max_x, max_y, '*', label=star_label, color='#FF7F00')
ax2.set_xlim([(max_x - 50), (max_x + 50)])
legend = ax2.legend(loc='lower center', shadow=True, fontsize='x-small')
# legend.get_frame().set_facecolor('')
plt.savefig(save_to)
示例8: makePlot
def makePlot(filename, xkcd, data):
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
data.sort(key=lambda x: x[1]) # sort the data, helps the pie
labels = [m[0] for m in data] # extract the labels
sizes = [m[1] for m in data] # extract the values
# make better colors and cycle through them
cmap = plt.cm.GnBu # http://matplotlib.org/examples/color/colormaps_reference.html
colors = cmap(np.linspace(0., 0.75, len(sizes)))
fig = plt.figure()
if xkcd:
plt.xkcd() # uncomment for xkcd style plots
plt.pie(sizes, labels=labels, autopct='%1.1f%%',
startangle=0, # this helps with the labels of the small slices
wedgeprops={'linewidth':'0'}, # makes the pie look nicer
colors = colors, # use our pretty colors
textprops={'fontsize':'x-small'}) # make the %s small to fit in pies
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
fig.savefig(filename, format="png")
示例9: _plot_mesh
def _plot_mesh(self, mesh, options):
'Plot the mesh.'
gdim = mesh.geometry().dim()
if gdim < 2:
raise ValueError('Invalid geometrical dimension. Must be > 1.')
# Optionally turn on xkcd
xkcd = options['xkcd']
if xkcd:
plt.xkcd()
fig = plt.figure()
# Get axes based on 2d or 3d
ax = fig.gca(projection='3d') if gdim > 2 else fig.gca()
# Prepare axis labels
for i in range(gdim):
x = chr(ord('x') + i)
label = x if xkcd else ('$%s$' % x)
eval("ax.set_%slabel('%s')" % (x, label))
# Get colors for plotting edges
cmap = plt.get_cmap(options['colors']['mesh'])
edge_color = cmap(cmap.N/2)
bdr_edge_color = cmap(9*cmap.N/10)
# Plot the edges and get min/max of coordinate axis
x_min_max = self._plot_edges(ax, mesh, edge_color, bdr_edge_color)
# Fix the limits for figure
for i in range(gdim):
xi_min, xi_max = x_min_max[i]
eval('ax.set_%slim(%g, %g)' % (chr(ord('x') + i), xi_min, xi_max))
return fig
示例10: main
def main():
__handdrawn__ = True
if __handdrawn__:
from matplotlib import pyplot as plt
plt.xkcd()
ohms = circuit.Circuit('resources/node_voltage.crt')
ohms.create_nodes()
ohms.populate_nodes()
ohms.identify_nontrivial_nodes()
ohms.create_branches()
ohms.create_supernodes()
ohms.sub_super_nodes()
ohms.identify_nontrivial_nonsuper_nodes() # TODO some of these should be moved to solver later
schem = drawer.Schematic(ohms)
schem.draw_schem()
my_solution = solver.Solver(ohms)
my_solution.set_reference_voltage(my_solution.circuit.non_trivial_reduced_nodedict[0])
my_solution.identify_voltages()
my_solution.identify_currents()
#print("performing kcl at each of the nodes in the circuit:") #todo move to solver
#ohms.kcl_everywhere()
#ohms.ohms_law_where_easy()
my_solution.gen_node_voltage_eq()
#ohms.sub_zero_for_ref()
my_solution.determine_known_vars()
my_solution.sub_into_eqs()
my_solution.solve_subbed_eqs()
#print(ohms.nodelist)
#print(ohms.num_nodes)
#print(ohms.netlist)
vivias = solver.Teacher(my_solution)
vivias.explain()
示例11: makeFig
def makeFig(data=None, scaleFactor=1, datarate=3200):
"""
prints the acquired data
"""
if docArgs['--xkcd']: plt.xkcd()
time = len(data)/float(datarate)
fig, ax1 = plt.subplots()
ax1.axis('auto')
plt.ylabel("Acceleration (g)")
plt.xlabel("Time (s)")
ax1.grid(True)
try:
timestep = np.linspace(0,time,len(data))
ax1.plot(timestep, [dat[0] for dat in data], 'r-', label='X Axis Values', lw=0.5)
ax1.plot(timestep, [dat[1] for dat in data], 'b-', label='Y Axis Values', lw=0.5)
ax1.plot(timestep, [dat[2] for dat in data], 'g-', label='Z Axis Values', lw=0.5)
except:
data = np.delete(data,0,0)
timestep = np.linspace(0,time,len(data))
#data2 = np.trapz(data[:,0])
ax1.plot(timestep, [dat[0] for dat in data], 'r-', label='X Axis Values', lw=0.5)
ax1.plot(timestep, [dat[1] for dat in data], 'b-', label='Y Axis Values', lw=0.5)
ax1.plot(timestep, [dat[2] for dat in data], 'g-', label='Z Axis Values', lw=0.5)
ax2 = ax1.twinx()
#ax2.plot(timestep, velocity, 'k-', label='Velocity', lw=0.5)
ax1.legend(loc='lower right')
plt.show()
示例12: run_plot
def run_plot(num_pts=100, maximize=False, interval_secs=5, xaxis_fmt='%I:%M'):
"""Runs the interactive plot of potato load"""
matplotlib.rcParams['toolbar'] = 'None'
if maximize:
mng = plt.get_current_fig_manager()
mng.resize(*mng.window.maxsize())
plt.gcf().canvas.set_window_title(' ')
plt.xkcd()
plt.ion()
plt.show()
data = [collections.deque([load], num_pts) for load in get_loads()]
times = collections.deque([datetime.datetime.now()], num_pts)
seaborn.set_palette('Set2', len(data))
while True:
for loads, new_load in zip(data, get_loads()):
loads.append(new_load)
times.append(datetime.datetime.now())
plt.clf()
for loads in data:
plt.plot(times, loads)
plt.title('AML Lab Cluster Loads', fontsize=60)
plt.gca().xaxis.set_major_formatter(dates.DateFormatter(xaxis_fmt))
plt.draw()
time.sleep(interval_secs)
示例13: main
def main(argv):
filename = argv[1]
f = open(filename, 'r')
data = []
for line in f:
d = [ float(e) for e in line.split('\t')]
data.append(d)
f.close()
d = dict()
for row in data:
c = row[0]
gamma = row[1]
if c not in d:
d[c] = dict()
d[c][gamma] = row[2]
# set up styles
styles = ['r', 'g', 'b', 'k', 'y', 'm', 'c']
styles = [ s + ":" for s in styles ] + [s + "--" for s in styles] #+ [s + "-." for s in styles]
random.shuffle(styles)
styles = styles*3
plt.xkcd()
for (c, style) in zip(d, styles):
gs = sorted([k for k in d[c]])
y = [d[c][v] for v in gs]
x = [log(x) for x in gs]
plt.plot(x, y, style+"o", label=str(c))
plt.legend()
plt.xticks(x, gs, rotation='vertical')
plt.show()
示例14: __init__
def __init__(self,
timelines,
custom,
showWindow=True,
registry=None):
""":param timelines: The timelines object
:type timelines: TimeLineCollection
:param custom: A CustomplotInfo-object. Values in this object usually override the
other options
"""
MatplotlibTimelines.__init__(self,
timelines,
custom,
showWindow=showWindow,
registry=registry
)
from matplotlib import pyplot
try:
pyplot.xkcd()
except AttributeError:
from matplotlib import __version__
warning("Installed version",__version__,
" of Matplotlib does not support XKCD-mode (this is supported starting with version 1.3). Falling back to normal operations")
开发者ID:Unofficial-Extend-Project-Mirror,项目名称:openfoam-extend-Breeder-other-scripting-PyFoam,代码行数:25,代码来源:XkcdMatplotlibTimelines.py
示例15: setup_figure
def setup_figure(self):
"""
Prepare the matplotlib figure for plotting.
This method sets the default font, and the overall apearance of the
figure.
"""
if options.cfg.xkcd:
fonts = QtGui.QFontDatabase().families()
for x in ["Humor Sans", "DigitalStrip", "Comic Sans MS"]:
if x in fonts:
self.options["figure_font"] = QtGui.QFont(x, pointSize=self.options["figure_font"].pointSize())
break
else:
for x in ["comic", "cartoon"]:
for y in fonts:
if x.lower() in y.lower():
self.options["figure_font"] = QtGui.QFont(x, pointSize=self.options["figure_font"].pointSize())
break
plt.xkcd()
with sns.plotting_context("paper"):
self.g = sns.FacetGrid(self._table,
col=self._col_factor,
col_wrap=self._col_wrap,
row=self._row_factor,
sharex=True,
sharey=True)