网络编程
位置:首页>> 网络编程>> Python编程>> Python绘图示例程序中的几个语法糖果你知道吗

Python绘图示例程序中的几个语法糖果你知道吗

作者:卓晴  发布时间:2021-01-18 17:15:25 

标签:Python,绘图,语法,糖果

01 示例函数

1.1 代码及结果

import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

def midpoints(x):
  sl = ()
  for i in range(x.ndim):
      x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
      sl += np.index_exp[:]
  return x

# prepare some coordinates, and attach rgb values to each
r, theta, z = np.mgrid[0:1:11j, 0:np.pi*2:25j, -0.5:0.5:11j]
x = r*np.cos(theta)
y = r*np.sin(theta)

rc, thetac, zc = midpoints(r), midpoints(theta), midpoints(z)

# define a wobbly torus about [0.7, *, 0]
sphere = (rc - 0.7)**2 + (zc + 0.2*np.cos(thetac*2))**2 < 0.2**2

# combine the color components
hsv = np.zeros(sphere.shape + (3,))
hsv[..., 0] = thetac / (np.pi*2)
hsv[..., 1] = rc
hsv[..., 2] = zc + 0.5
colors = matplotlib.colors.hsv_to_rgb(hsv)

# and plot everything
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(x, y, z, sphere,
        facecolors=colors,
        edgecolors=np.clip(2*colors - 0.5, 0, 1),  # brighter
        linewidth=0.5)

plt.show()

Python绘图示例程序中的几个语法糖果你知道吗

绘制的3D图像

1.2 Python函数

在代码中,包括有以下几个函数值得进一步的探究,以备之后学习和应用。

  • np.index_exp:产生array 的索引元组;

  • shape() + (3,) : 对于一个元组增加维度;

  • 省略号: 自适应数组索引;

语法糖 (Syntactic Sugar)是为了方便编程人员使用的变化的语法,它并不对原来的功能产生任何影响。

比如:

  • a[i] : *(a+i)

  • a[i][j] : (a+icol +j)

02 数组索引

2.1 省略号

利用省略号,可以自适应匹配前面省略的数组索引。

下面定义了一个3D数字:x。

import sys,os,math,time
import matplotlib.pyplot as plt
from numpy import *

x = array([[[1],[2],[3]], [[4],[5],[6]]])
print("x: {}".format(x), "x.shape: {}".format(x.shape))
x: [[[1]
 [2]
 [3]]

[[4]
 [5]
 [6]]]
x.shape: (2, 3, 1)

下面通过省略号访问x,可以看到它与前面补齐索引是相同的效果。

x1 = x[...,0]
x2 = x[:,:,0]
print("x1: {}".format(x1),"x2: {}".format(x2))
x1.shape: (2, 1, 3, 1)
x2.shape: (2, 1, 3, 1)

2.2 扩增数组维度

扩增数组维度,可以使用一下两个等效的语法来完成。

x1 = x[:,None,:,:]
x2 = x[:,newaxis,:,:]
print("x1.shape: {}".format(x1.shape), "x2.shape: {}".format(x2.shape))
x1.shape: (2, 1, 3, 1)
x2.shape: (2, 1, 3, 1)

2.3 元组相加

元组可以通过&ldquo;+&rdquo;串联在一起:

a = (1,2,3)
b = (1,)
print(a+b)
(1, 2, 3, 1)

实际上对于列表也是可以的:

a = [1,2,3]
b = [1]
print(a+b)
[1, 2, 3, 1]

但是list 与 tuple 不能够叠加:

a = [1,2,3]
b = (1,)
print(a+b)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_164/1922126339.py in <module>
     5 a = [1,2,3]
     6 b = (1,)
----> 7 printt(a+b)

TypeError: can only concatenate list (not "tuple") to list

2.4 一维变二维

import numpy
a = array([1,2,3,4])
b = array([5,6,7,8])
d = numpy.r_[a,b]
print("d: {}".format(d))

d: [1 2 3 4 5 6 7 8] 

import numpy
a = array([1,2,3,4])
b = array([5,6,7,8])
d = numpy.c_[a,b]
print("d: {}".format(d))

d: [[1 5]
 [2 6]
 [3 7]
 [4 8]]

来源:https://blog.csdn.net/zhuoqingjoking97298/article/details/122866323

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com