python图形绘制源代码.doc

上传人:豆**** 文档编号:33507396 上传时间:2022-08-11 格式:DOC 页数:28 大小:1.50MB
返回 下载 相关 举报
python图形绘制源代码.doc_第1页
第1页 / 共28页
python图形绘制源代码.doc_第2页
第2页 / 共28页
点击查看更多>>
资源描述

《python图形绘制源代码.doc》由会员分享,可在线阅读,更多相关《python图形绘制源代码.doc(28页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、-作者xxxx-日期xxxxpython图形绘制源代码【精品文档】饼图import matplotlib.pyplot as plt# Pie chart, where the slices will be ordered and plotted counter-clockwise:labels = Frogs, Hogs, Dogs, Logssizes = 15, 30, 45, 10explode = (0, 0.1, 0, 0) # only explode the 2nd slice (i.e. Hogs)fig1, ax1 = plt.subplots()ax1.pie(sizes

2、, explode=explode, labels=labels, autopct=%1.1f%, shadow=True, startangle=90)ax1.axis(equal) # Equal aspect ratio ensures that pie is drawn as a circle.plt.show()条形图1import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocatorfrom collections import namedtuplen_groups =

3、 5means_men = (20, 35, 30, 35, 27)std_men = (2, 3, 4, 1, 2)means_women = (25, 32, 34, 20, 25)std_women = (3, 5, 2, 3, 3)fig, ax = plt.subplots()index = np.arange(n_groups)error_config = ecolor: 0.3rects1 = ax.bar(index, means_men, bar_width, alpha=opacity, color=b, yerr=std_men, error_kw=error_confi

4、g, label=Men)rects2 = ax.bar(index + bar_width, means_women, bar_width, alpha=opacity, color=r, yerr=std_women, error_kw=error_config, label=Women)ax.set_xlabel(Group)ax.set_ylabel(Scores)ax.set_title(Scores by group and gender)ax.set_xticks(index + bar_width / 2)ax.set_xticklabels(A, B, C, D, E)ax.

5、legend()fig.tight_layout()plt.show()表格图import numpy as npimport matplotlib.pyplot as pltdata = 66386, 174296, 75131, 577908, 32015, 58230, 381139, 78045, 99308, 160454, 89135, 80552, 152558, 497981, 603535, 78415, 81858, 150656, 193263, 69638, 139361, 331509, 343164, 781380, 52269columns = (Freeze,

6、Wind, Flood, Quake, Hail)rows = %d year % x for x in (100, 50, 20, 10, 5)values = np.arange(0, 2500, 500)value_increment = 1000# Get some pastel shades for the colorscolors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)n_rows = len(data)# Initialize the vertical-offset for the stacked bar chart.y_offse

7、t = np.zeros(len(columns)# Plot bars and create text labels for the tablecell_text = for row in range(n_rows): plt.bar(index, datarow, bar_width, bottom=y_offset, color=colorsrow) y_offset = y_offset + datarow cell_text.append(%1.1f % (x / 1000.0) for x in y_offset)# Reverse colors and text labels t

8、o display the last value at the top.colors = colors:-1cell_text.reverse()# Add a table at the bottom of the axesthe_table = plt.table(cellText=cell_text, rowLabels=rows, rowColours=colors, colLabels=columns, loc=bottom)# Adjust layout to make room for the table:plt.subplots_adjust(left=0.2, bottom=0

9、.2)plt.ylabel(Loss in $0s.format(value_increment)plt.yticks(values * value_increment, %d % val for val in values)plt.xticks()plt.title(Loss by Disaster)plt.show()散点图import numpy as npimport matplotlib.pyplot as pltimport matplotlib.cbook as cbook# Load a numpy record array from yahoo csv data with f

10、ields date, open, close,# volume, adj_close from the mpl-data/example directory. The record array# stores the date as an np.datetime64 with a day unit (D) in the date column.with cbook.get_sample_data(goog.npz) as datafile: price_data = np.load(datafile)price_data.view(np.recarray)price_data = price

11、_data-250: # get the most recent 250 trading daysdelta1 = np.diff(price_data.adj_close) / price_data.adj_close:-1# Marker size in units of points2volume = (15 * price_data.volume:-2 / price_data.volume0)*2close = 0.003 * price_data.close:-2 / 0.003 * price_data.open:-2fig, ax = plt.subplots()ax.scat

12、ter(delta1:-1, delta11:, c=close, s=volume, alpha=0.5)ax.set_xlabel(r$Delta_i$, fontsize=15)ax.set_ylabel(r$Delta_i+1$, fontsize=15)ax.set_title(Volume and percent change)ax.grid(True)fig.tight_layout()plt.show()平滑图import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Slide

13、r, Button, RadioButtonsfig, ax = plt.subplots()plt.subplots_adjust(left=0.25, bottom=0.25)t = np.arange(0.0, 1.0, 0.001)a0 = 5f0 = 3s = a0*np.sin(2*np.pi*f0*t)l, = plt.plot(t, s, lw=2, color=red)plt.axis(0, 1, -10, 10)axcolor = lightgoldenrodyellowaxfreq = plt.axes(0.25, 0.1, 0.65, 0.03, facecolor=a

14、xcolor)axamp = plt.axes(0.25, 0.15, 0.65, 0.03, facecolor=axcolor)sfreq = Slider(axfreq, Freq, 0.1, 30.0, valinit=f0, valstep=delta_f)samp = Slider(axamp, Amp, 0.1, 10.0, valinit=a0)def update(val): l.set_ydata(amp*np.sin(2*np.pi*freq*t) fig.canvas.draw_idle()sfreq.on_changed(update)samp.on_changed(

15、update)resetax = plt.axes(0.8, 0.025, 0.1, 0.04)button = Button(resetax, Reset, color=axcolor, hovercolor=0.975)def reset(event): sfreq.reset() samp.reset()button.on_clicked(reset)rax = plt.axes(0.025, 0.5, 0.15, 0.15, facecolor=axcolor)radio = RadioButtons(rax, (red, blue, green), active=0)def colo

16、rfunc(label): l.set_color(label) fig.canvas.draw_idle()radio.on_clicked(colorfunc)plt.show()数据打钩标签图import datetimeimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbookyears = mdates.YearLocator() # every yearmonths = mdates.MonthLocator()

17、# every monthyearsFmt = mdates.DateFormatter(%Y)# Load a numpy record array from yahoo csv data with fields date, open, close,# volume, adj_close from the mpl-data/example directory. The record array# stores the date as an np.datetime64 with a day unit (D) in the date column.with cbook.get_sample_da

18、ta(goog.npz) as datafile: r = np.load(datafile)price_data.view(np.recarray)fig, ax = plt.subplots()ax.plot(r.date, r.adj_close)# format the ticksax.xaxis.set_major_locator(years)ax.xaxis.set_major_formatter(yearsFmt)ax.xaxis.set_minor_locator(months)# round to nearest years.datemin = np.datetime64(r

19、.date0, Y)datemax = np.datetime64(r.date-1, Y) + np.timedelta64(1, Y)ax.set_xlim(datemin, datemax)# format the coords message boxdef price(x): return $%1.2f % xax.format_xdata = mdates.DateFormatter(%Y-%m-%d)ax.format_ydata = priceax.grid(True)# rotates and right aligns the x labels, and moves the b

20、ottom of the# axes up to make room for themfig.autofmt_xdate()plt.show()使用预定义标签的图例import numpy as npimport matplotlib.pyplot as plt# Make some fake data.a = b = np.arange(0, 3, .02)c = np.exp(a)d = c:-1# Create plots with pre-defined labels.fig, ax = plt.subplots()ax.plot(a, c, k-, label=Model lengt

21、h)ax.plot(a, d, k:, label=Data length)ax.plot(a, c + d, k, label=Total message length)legend = ax.legend(loc=upper center, shadow=True, fontsize=x-large)# Put a nicer background color on the legend.legend.get_frame().set_facecolor(#00FFCC)plt.show()数学公式编辑图from _future_ import print_functionimport ma

22、tplotlib.pyplot as pltimport subprocessimport sysimport reimport gc# Selection of features following Writing mathematical expressions tutorialmathtext_titles = 0: Header demo, 1: Subscripts and superscripts, 2: Fractions, binomials and stacked numbers, 3: Radicals, 4: Fonts, 5: Accents, 6: Greek, He

23、brew, 7: Delimiters, functions and Symbolsn_lines = len(mathtext_titles)# Randomly picked examplesmathext_demos = 0: r$W3beta_delta_1 rho_1 sigma_2 = rU3beta_delta_1 rho_1 + frac18 pi 2 rintalpha_2_alpha_2 d alphaprime_2 leftfrac rU2beta_delta_1 rho_1 - alphaprime_2U1beta_ rrho_1 sigma_2 U0beta_rho_

24、1 sigma_2right$, 1: r$alpha_i beta_i, ralpha_i+1j = rm sin(2pi f_j t_i) e-5 t_i/tau, rldots$, 2: r$frac34, binom34, stackrel34, rleft(frac5 - frac1x4right), ldots$, 3: r$sqrt2, sqrt3x, ldots$, 4: r$mathrmRoman , mathitItalic , mathttTypewriter rmathrmor mathcalCALLIGRAPHY$, 5: r$acute a, bar a, brev

25、e a, dot a, ddot a, grave a, rhat a, tilde a, vec a, widehatxyz, widetildexyz, rldots$, 6: r$alpha, beta, chi, delta, lambda, mu, rDelta, Gamma, Omega, Phi, Pi, Upsilon, nabla, raleph, beth, daleth, gimel, ldots$, 7: r$coprod, int, oint, prod, sum, rlog, sin, approx, oplus, star, varpropto, rinfty,

26、partial, Re, leftrightsquigarrow, ldots$def doall(): # Colors used in mpl online documentation. mpl_blue_rvb = (191. / 255., 209. / 256., 212. / 255.) mpl_orange_rvb = (202. / 255., 121. / 256., 0. / 255.) mpl_grey_rvb = (51. / 255., 51. / 255., 51. / 255.) # Creating figure and axis. plt.figure(fig

27、size=(6, 7) plt.axes(0.01, 0.01, 0.98, 0.90, facecolor=white, frameon=True) plt.gca().set_xlim(0., 1.) plt.gca().set_ylim(0., 1.) plt.gca().set_title(Matplotlibs math rendering engine, color=mpl_grey_rvb, fontsize=14, weight=bold) plt.gca().set_xticklabels(, visible=False) plt.gca().set_yticklabels(

28、, visible=False) # Gap between lines in axes coords line_axesfrac = (1. / (n_lines) # Plotting header demonstration formula full_demo = mathext_demos0 plt.annotate(full_demo, xy=(0.5, 1. - 0.59 * line_axesfrac), xycoords=data, color=mpl_orange_rvb, ha=center, fontsize=20) # Plotting features demonst

29、ration formulae for i_line in range(1, n_lines): baseline = 1 - (i_line) * line_axesfrac baseline_next = baseline - line_axesfrac title = mathtext_titlesi_line + : fill_color = white, mpl_blue_rvbi_line % 2 plt.fill_between(0., 1., baseline, baseline, baseline_next, baseline_next, color=fill_color,

30、alpha=0.5) plt.annotate(title, xy=(0.07, baseline - 0.3 * line_axesfrac), xycoords=data, color=mpl_grey_rvb, weight=bold) demo = mathext_demosi_line plt.annotate(demo, xy=(0.05, baseline - 0.75 * line_axesfrac), xycoords=data, color=mpl_grey_rvb, fontsize=16) for i in range(n_lines): s = mathext_dem

31、osi print(i, s) plt.show()if -latex in sys.argv: # Run: python mathtext_examples.py -latex # Need amsmath and amssymb packages. fd = open(mathtext_examples.ltx, w) fd.write(documentclassarticlen) fd.write(usepackageamsmath, amssymbn) fd.write(begindocumentn) fd.write(beginenumeraten) for i in range(

32、n_lines): s = mathext_demosi s = re.sub(r(?), xytext=(15, -10) plt.plot(data) plt.xlabel(time) plt.ylabel(my overall health) fig.text( 0.5, 0.05, Stove Ownership from xkcd by Randall Monroe, ha=center)with plt.xkcd(): # Based on The Data So Far from XKCD by Randall Monroe fig = plt.figure() ax = fig

33、.add_axes(0.1, 0.2, 0.8, 0.7) ax.bar(0, 1, 0, 100, 0.25) ax.spinesright.set_color(none) ax.spinestop.set_color(none) ax.xaxis.set_ticks_position(bottom) ax.set_xticks(0, 1) ax.set_xlim(-0.5, 1.5) ax.set_ylim(0, 110) ax.set_xticklabels(CONFIRMED BYnEXPERIMENT, REFUTED BYnEXPERIMENT) plt.yticks() plt.

34、title(CLAIMS OF SUPERNATURAL POWERS) fig.text( 0.5, 0.05, The Data So Far from xkcd by Randall Monroe, ha=center)plt.show()样本子图import matplotlib.pyplot as pltimport numpy as npnp.random.seed(19680801)data = np.random.randn(2, 100)fig, axs = plt.subplots(2, 2, figsize=(5, 5)axs0, 0.hist(data0)axs1, 0

35、.scatter(data0, data1)axs0, 1.plot(data0, data1)axs1, 1.hist2d(data0, data1)plt.show()极图import numpy as npimport matplotlib.pyplot as pltr = np.arange(0, 2, 0.01)theta = 2 * np.pi * rax = plt.subplot(111, projection=polar)ax.plot(theta, r)ax.set_rmax(2)ax.set_rticks(0.5, 1, 1.5, 2) # Less radial tic

36、ksax.set_rlabel_position(-22.5) # Move radial labels away from plotted lineax.grid(True)ax.set_title(A line plot on a polar axis, va=bottom)plt.show()Log图import numpy as npimport matplotlib.pyplot as plt# Data for plottingt = np.arange(0.01, 20.0, 0.01)# Create figurefig, (ax1, ax2), (ax3, ax4) = plt.subplots(2, 2)# log y axisax1.semilogy(t, np.exp(-t / 5.0)ax1.set(title=semilogy)ax1.grid()# log x axisax2.semilogx(t, np.sin(2 * np.pi * t)ax2.set(title=semilogx)ax2.grid()# log x and y axisax3.loglog(t, 20 * np.exp(-t / 10.0), basex

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 高考资料

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com