我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用matplotlib.pyplot.xkcd()。
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)
def reset_plt(self): """ Reset the current matplotlib plot style. """ import matplotlib.pyplot as plt plt.gcf().subplots_adjust(bottom=0.15) if Settings()["report/xkcd_like_plots"]: import seaborn as sns sns.reset_defaults() mpl.use("agg") plt.xkcd() else: import seaborn as sns sns.reset_defaults() sns.set_style("darkgrid") sns.set_palette(sns.color_palette("muted")) mpl.use("agg")
def visualize(info, timestamp, data, label="", dayrange=2,annotate=True): plt.xkcd() count = len(timestamp) number = range(count) submit = timestamp[0] plt.plot(timestamp,number,"-",lw=3,label=label) plt.xlim(submit,submit+datetime.timedelta(days=dayrange)) if annotate: plt.annotate(data,xy=(timestamp[-1], number[-1]), arrowprops=dict(arrowstyle='->'), xytext=(timestamp[-1],5))
def cdf_prep(node, _): """Write a graph of the cdf of @p node to the current pyplot.""" # pylint: disable = invalid-name plt.xkcd() cost = node.final_cost() (x_min, x_max) = bounds_for_plotting(cost) xs = linspace(x_min, x_max, NUM_SAMPLES, endpoint=True) ys = [cost.cdf(x) for x in xs] cubic_y = interp1d(xs, ys, kind="cubic") xs_dense = linspace(x_min, x_max, GRAPH_RESOLUTION, endpoint=True) plt.plot(xs_dense, cubic_y(xs_dense), '-')
def plotStats(self, res, value, title): # plt.xkcd() self.Ax.clear() plotDataX= [] plotDataY= [] for el in self.plotList: plotDataX.append(float(el[res])) plotDataY.append(float(el[value].strip('*').strip('%'))) self.Ax.plot(plotDataX, plotDataY, 'r-^') self.Ax.set_xlim(10,0) self.Ax.set_title(title) self.statsCanvas.draw()
def plot(weights, height=1.92, xkcd=False, target_bmi=None, long_dates=False, plot=True, save=False, outfile="out.png", show_bmi_steps=True): if xkcd: plt.xkcd() timestamps = [w['time'] for w in weights] weight_points = [w['weight'] for w in weights] dates=[datetime.datetime.fromtimestamp(ts) for ts in timestamps] ax=plt.gca() date_format = "%d.%m.%Y" if long_dates else "%d.%m." xfmt = md.DateFormatter(date_format) ax.xaxis.set_major_formatter(xfmt) plt.scatter(dates,weight_points, zorder=2) x_sm = np.array(timestamps) y_sm = np.array(weight_points) seconds_diff = max(timestamps) - min(timestamps) num_steps = seconds_diff / 60 / 60 / 24 / 28 # one step every four weeks x_smooth = np.linspace(x_sm.min(), x_sm.max(), num_steps) y_smooth = interp1d(timestamps, weight_points, kind='linear') x_smooth_dates = [datetime.datetime.fromtimestamp(ts) for ts in x_smooth] plt.plot(x_smooth_dates, y_smooth(x_smooth), 'red', linewidth=1, zorder=1) if target_bmi: ax.add_line(plt.axhline(target_bmi*(height**2))) plt.axis('normal') ax.set_ylabel("Weight (kg)",fontsize=14,color='black') ax.set_xlabel('Time', fontsize=14, color='b') if show_bmi_steps: ax2 = ax.twinx() ax2.tick_params(which = 'both', direction = 'out') ax2.set_ylabel("BMI",fontsize=14,color='black') wmin, wmax = ax.get_ylim() bmin = wmin/(height**2) bmax = wmax/(height**2) ax2.set_ylim(ymin=bmin, ymax=bmax) step_size = 0.5 st = math.ceil(bmin/step_size) * 0.5 minor_ticks = np.arange(st, bmax, step_size) ax2.set_yticks(minor_ticks, minor=True) ax2.grid(which='minor', alpha=0.5) ax2.grid(which='major', alpha=0.75) if plot: plt.show() if save: plt.savefig(outfile, bbox_inches='tight') # close plot so we can draw multiple plots without reimportint pyplot plt.close()
def multi_cdf_prep(node, _): """Plot the CDF of @p node, with subdivisions representing the sequence of child nodes. NOTE: The subdivision plots, though pretty, are not mathematically well-founded: Later plots gain more central-limit-theorem love than earlier ones, and so the overall node variance will appear to be overattributed to the earlier subtasks and underattributed to the later ones. """ # pylint: disable = invalid-name, too-many-locals plt.xkcd() axes = plt.axes() axes.set_xlabel("Cost of \"" + node.data[:20] + "\"") axes.set_ylabel("Likelihood") colors = ["red", "blue", "black"] hatches = ["/", "\\", "o", "-"] total_cost = node.final_cost() axes.set_title(" : ".join("%d" % round(node.final_cost().quantile(q / 100)) for q in (10, 25, 50, 75, 90))) cost_so_far = distribution.ZERO (x_min, x_max) = bounds_for_plotting(total_cost) xs = linspace(x_min, x_max, NUM_SAMPLES, endpoint=True) xs_dense = linspace(x_min, x_max, GRAPH_RESOLUTION, endpoint=True) curves = [] nodes_to_plot = [child for child in node.children if child.has_cost()] for to_plot in nodes_to_plot: cost_so_far = dist_add(cost_so_far, to_plot.final_cost()) curves.append(([cost_so_far.cdf(x) for x in xs], to_plot.get_display_name()[:20])) if node.distribution: # Direct cost in a node with costly children: Odd but not prohibited. curves.append((total_cost, node.get_display_name()[:20])) legend = [] prior_ys = 1.0 for (ys, name) in curves: cubic_y = interp1d(xs, ys, kind="cubic") axes.plot(xs_dense, cubic_y(xs_dense), '-', color=colors[0]) axes.fill_between(xs, prior_ys, ys, hatch=hatches[0], edgecolor=colors[0], facecolor="white") legend.append(name) colors = colors[1:] + colors[0:1] hatches = hatches[1:] + hatches[0:1] prior_ys = ys axes.legend(legend)
def test(): from io import BytesIO x = [datetime.datetime(2017, 4, 6, 0, 0), datetime.datetime(2017, 4, 7, 0, 0), datetime.datetime(2017, 4, 8, 0, 0), datetime.datetime(2017, 4, 11, 0, 0), datetime.datetime(2017, 4, 12, 0, 0), datetime.datetime(2017, 4, 13, 0, 0), datetime.datetime(2017, 4, 14, 0, 0), datetime.datetime(2017, 4, 16, 0, 0), datetime.datetime(2017, 4, 17, 0, 0), datetime.datetime(2017, 4, 18, 0, 0), datetime.datetime(2017, 4, 19, 0, 0), datetime.datetime(2017, 4, 20, 0, 0), datetime.datetime(2017, 4, 22, 0, 0), datetime.datetime(2017, 4, 23, 0, 0)] y = [[0.0, 15.0, 9.0, 0.0, 9.0, 5.0, 6.0, 0.0, 11.0, 9.0, 5.0, 6.0, 0.0, 11.0], [15.0, 17.0, 0.0, 20.0, 20.0, 19.0, 30.0, 32.0, 23.0, 20.0, 19.0, 30.0, 32.0, 23.0]] grid = [ [{'date': datetime.datetime(2017, 4, 3, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 4, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 5, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 6, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 15.]}, {'date': datetime.datetime(2017, 4, 7, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 15., 17.]}, {'date': datetime.datetime(2017, 4, 8, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 9., 0.]}, {'date': datetime.datetime(2017, 4, 9, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}], [{'date': datetime.datetime(2017, 4, 10, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 11, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 20.]}, {'date': datetime.datetime(2017, 4, 12, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 9., 20.]}, {'date': datetime.datetime(2017, 4, 13, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 5., 19.]}, {'date': datetime.datetime(2017, 4, 14, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 6., 30.]}, {'date': datetime.datetime(2017, 4, 15, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 16, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 32.]}], [{'date': datetime.datetime(2017, 4, 17, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 11., 23.]}, {'date': datetime.datetime(2017, 4, 18, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 19, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 20, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 21, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 22, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 23, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}], [{'date': datetime.datetime(2017, 4, 24, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 11., 23.]}, {'date': datetime.datetime(2017, 4, 25, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 26, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 27, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 28, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 29, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}, {'date': datetime.datetime(2017, 4, 30, 0, 0, tzinfo=tzoffset(None, 10800)), 'values': [ 0., 0.]}] ] dashboard = { "summary": "Anna work-out", "empty_image": "../amazon-dash-private/images/old-woman.png", "images_folder": "../amazon-dash-private/images/" } labels = [ {"summary": "Morning work-out", "image": "../amazon-dash-private/images/morning4.png"}, {"summary": "Physiotherapy", "image": "../amazon-dash-private/images/evening2.png"} ] absent_labels = [ {'image_grid': '../amazon-dash-private/images/absent_ill_grid.png', 'image_plot': '../amazon-dash-private/images/absent_ill_plot.png', 'summary': 'Sick'}, {'image_grid': '../amazon-dash-private/images/absent_vacation_grid.png', 'image_plot': '../amazon-dash-private/images/absent_vacation_plot.png', 'summary': 'Vacation'} ] weather = {'day': [datetime.datetime(2017, 4, 22, 0, 0), datetime.datetime(2017, 4, 23, 0, 0), datetime.datetime(2017, 4, 24, 0, 0), datetime.datetime(2017, 4, 25, 0, 0)], 'icon': ['sct', 'ovc', 'hi_shwrs', 'sn'], 'temp_max': [6.64, 6.38, 4.07, 6.91], 'temp_min': [-0.58, -2.86, -1.87, -1.91], 'images_folder': '../amazon-dash-private/images/'} t0 = datetime.datetime.now() image_data = draw_calendar(grid, x, y, weather, dashboard, labels, absent_labels, ImageParams( dashboard='', format='gif', style='seaborn-talk', xkcd=1, rotate=0 ) ) t1 = datetime.datetime.now() print(t1 - t0) image_file = BytesIO(image_data) image = PIL.Image.open(image_file) image.show() # with open('test.png', 'wb') as png_file: # png_file.write(image) #plt.show() #todo speed it up. too many rescalings as I see from profiling. # may be using artists (http://stackoverflow.com/questions/41453902/is-it-possible-to-patch-an-image-in-matplotlib) # will reduce number of rescaling? # now it looks like matplotlib rescales after each operation