GVKun编程网logo

numpy 与 matplotlib 的应用过程(numpy和matplotlib关系)

1

在这篇文章中,我们将为您详细介绍numpy与matplotlib的应用过程的内容,并且讨论关于numpy和matplotlib关系的相关问题。此外,我们还会涉及一些关于Eclipse中的Matplot

在这篇文章中,我们将为您详细介绍numpy 与 matplotlib 的应用过程的内容,并且讨论关于numpy和matplotlib关系的相关问题。此外,我们还会涉及一些关于Eclipse 中的 Matplotlib.axes 与 matplotlib.pyplot.axes、Help on module matplotlib.cm in matplotlib:、Jupyterlab / Notebook 中的交互式 matplotlib 图(使用 ipympl 的 %matplotlib 小部件)仅工作一次然后消失、matplotlib - 数据框 - 如何在 matplotlib 的背景上有真实的地图的知识,以帮助您更全面地了解这个主题。

本文目录一览:

numpy 与 matplotlib 的应用过程(numpy和matplotlib关系)

numpy 与 matplotlib 的应用过程(numpy和matplotlib关系)

numpy 与 matplotlib 的应用

一、库函数介绍

1. numpy 库

  NumPy(Numeric Python)提供了一个 N 维的数组类型 ndarray,Numpy 底层使用 C 语言编写,内部解除了 GIL(全局解释器锁),其对数组的操作速度不受 Python 解释器的限制,效率远高于纯 Python 代码。

  ndarray 到底跟原生 python 列表的区别:

  ndarray 中的所有元素的类型都是相同的,而 Python 列表中的元素类型是任意的,所以 ndarray 在存储元素时内存可以连续,而 python 原生 list 就只能通过寻址方式找到下一个元素,这虽然也导致了在通用性能方面 Numpy 的 ndarray 不及 Python 原生 list,但在科学计算中,Numpy 的 ndarray 就可以省掉很多循环语句,代码使用方面比 Python 原生 list 简单的多。

2. matplotlib 库

  matplotlib 是一个 Python 的 2D 绘图库,也是 Python 编程语言及其数值数学扩展包 NumPy 的可视化操作界面。它利用通用的图形用户界面工具包,如 Tkinter, wxPython, Qt 或 GTK + 向应用程序嵌入式绘图提供了应用程序接口(API)。此外,matplotlib 还有一个基于图像处理库(如开放图形库 OpenGL)的 pylab 接口,其设计与 MATLAB 非常类似 -- 尽管并不怎么好用。SciPy 就是用 matplotlib 进行图形绘制。

 

二、应用 A

1. 介绍:对 python123 作业的成绩通过画图显示

2. 代码实现:

# -*- coding:utf-8 -*-
'''''' 成绩雷达图 ''''''
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams [''font.family''] = ''SimHei'' # 设置字体
plt.rcParams [''font.sans-serif''] = [''SimHei''] # 设置字体

labels = np.array (['' 第一周 '','' 第二周 '','' 第三周 '','' 第四周 '','' 第五周 '','' 第六周 '']) # 设置标签
datas = np.array ([0,9, 10, 10, 10, 8]) # 设置数据
angles = np.linspace (0, 2*np.pi, 6, endpoint = False) # 设置角度
datas = np.concatenate((datas, [datas[0]]))
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure (facecolor = ''white'') # 创建绘图区域
plt.subplot (111, polar = True) # 极坐标
plt.plot (angles, datas, ''bo-'', color = ''g'', linewidth = 1) # 画图
plt.fill (angles, datas, facecolor = ''g'', alpha = 0.25) # 填充
plt.thetagrids (angles*180/np.pi, labels) # 设置极坐标的位置
plt.figtext (0.52, 0.95, ''38 - 常欣 '', ha = ''center'') # 设置标题
plt.grid (True) # 打开网格线
plt.show () # 展示图片

 

3. 效果展示:

 

 

三、应用 B

1. 介绍:使用 numpy 和 PIL 库实现图像的手绘效果

2. 代码实现:

1 # -*- coding:utf-8 -*-
 2 '''''' 手绘图像效果 ''''''
 3 import numpy as np
 4 from PIL import Image
 5 vec_el = np.pi/2.2   # 光源的俯视角度,弧度值
 6 vec_az = np.pi/4.    # 光源的方位角度,弧度值
 7 depth = 6.          # 深度权值,值越小背景区域越接近白色,值越大背景区域越接近黑色
 8 im = Image.open(''PICTURE\HandMade.jpg'').convert(''L'')     # 打开图像并转变为灰度模式
 9 a = np.asarray(im).astype(''float'')
10 grad = np.gradient(a)              # 取图像灰度的梯度值
11 grad_x, grad_y = grad              # 分别取图像的横纵梯度值
12 grad_x = grad_x * depth / 100.
13 grad_y = grad_y * depth / 100.
14 dx = np.cos(vec_el) * np.cos(vec_az) # 光源对x轴的影响
15 dy = np.cos(vec_el) * np.sin(vec_az) # 光源对y轴的影响
16 dz = np.sin(vec_el)                  # 光源对z轴的影响
17 A = np.sqrt(grad_x**2 + grad_y**2 + 1.)
18 uni_x = grad_x/A
19 uni_y = grad_y/A
20 uni_z = 1./A
21 a2 = 255*(dx * uni_x + dy * uni_y + dz * uni_z) # 光源归一化
22 a2 = a2.clip(0, 255)                 # 预防溢出
23 im2 = Image.fromarray(a2.astype(''uint8''))       # 重构图像
24 im2.save(''HandMade_.jpg'') # 保存图像
25 im2.show()                # 显示图像

 

3. 效果展示:

                                           原图                                                                              效果图

 

四、应用 C

1. 简介:用 numpy 和 matplotlib 展现数学模型 —— 正态分布

2. 代码实现:

1 # -*- coding:utf-8 -*-
 2 '''''' 正态分布 ''''''
 3 import numpy as np
 4 import matplotlib.mlab as mlab
 5 import matplotlib.pyplot as plt
 6 
 7 dx = 100           # 正态分布的均值
 8 sigma = 15         # 标准差
 9 x = dx + sigma * np.random.randn(10000)  # 在均值周围产生符合正态分布的x值
10 
11 num_bins = 50
12 n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor=''green'', alpha=0.5)
13 # 直方图函数,x为x轴的值,normed=1表示为概率密度,即和为一,绿色方块,色深参数0.5.返回n个概率,直方块左边线的x值,及各个方块对象
14 y = mlab.normpdf(bins, dx, sigma)        # 画一条逼近的曲线
15 plt.plot(bins, y, ''r--'')
16 plt.xlabel(''Smarts'')                     # x轴标签
17 plt.ylabel(''Probability'')                # y轴标签
18 plt.title(r''Histogram of IQ: $\mu=100$, $\sigma=15$'') # 中文标题
19 
20 plt.subplots_adjust(left=0.15)           # 左边距
21 plt.grid(True)      # 打开网格线
22 plt.show()          # 显示图片

 

3. 效果展示:

Eclipse 中的 Matplotlib.axes 与 matplotlib.pyplot.axes

Eclipse 中的 Matplotlib.axes 与 matplotlib.pyplot.axes

如何解决Eclipse 中的 Matplotlib.axes 与 matplotlib.pyplot.axes

我试图理解为什么我的代码无法在 Eclipse IDE 中使用“.”运算符完成,即使代码运行成功。代码如下:

import matplotlib.pyplot as plt

# I can use either of these and get the same result. 
# ax = plt.subplot()                            #(1)
ax = plt.gca()                                  #(2) 

ax.plot(people,total_cost,color = ''red'')      #(3)
ax.set_xlabel(''# People'')                       #(4)
ax.set_ylabel(''Cost\\n(Parking)\\t(ticket)'')      #(5)

我不明白的是,虽然语句 (4) 和 (5) 相应地绘制了图形,但 ''ax'' 的属性根本不是来自 ''pyplot.axes'' 类,而是来自 ''matplotlib.axes'' 类。轴类。语句(3)是来自pyplot.axes的调用

接下来就是问题了。

  1. 为什么我不能使用“.”运算符来完成代码,即使每个在 (3)、(4) 和 (5) 中都是有效的语句?

2 虽然 ‘ax’ 可以定义为来自 ‘pyplot.axes’ 类的 (1) 或 (2),但语句 (3) 来自 ‘matplotlib.axes’ 类。那么如何成功调用两个类而不声明一个类作为 (1) 或 (2) 的结果?

  1. 就像注释一样,“matplotlib.axes”和“matplotlib.pyplot.axes”的参数似乎相同。

感谢您的帮助。

matplotlib.pyplot.plot https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html

matplotlib.pyplot.axes https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.axes.html

matplotlib.axes https://matplotlib.org/stable/api/axes_api.html

解决方法

matplotlib.pyplot.axes 是一个函数,而不是一个类。它创建 matplotlib.axes.Axes 类的一个实例,将其添加到当前图形,并使其成为当前轴。

matplotlib.axes 是一个模块,而不是一个类。它包含 matplotlib.axes.Axes 类,当您调用函数来创建 Axes 实例时会创建该类,例如 plt.subplots()fig.add_axes()plt.gca() 等。>

因此,无论您使用哪种方法 (1) 或 (2),您的 ax 都将是一个 matplotlib.axes.Axes 实例。

Help on module matplotlib.cm in matplotlib:

Help on module matplotlib.cm in matplotlib:

Help on module matplotlib.cm in matplotlib:

NAME
matplotlib.cm

FILE
d:\programdata\anaconda2\lib\site-packages\matplotlib\cm.py

DESCRIPTION
This module provides a large set of colormaps, functions for
registering new colormaps and for getting a colormap by name,
and a mixin class for adding color mapping functionality.

CLASSES
__builtin__.object
ScalarMappable

class ScalarMappable(__builtin__.object)
| This is a mixin class to support scalar data to RGBA mapping.
| The ScalarMappable makes use of data normalization before returning
| RGBA colors from the given colormap.
|
| Methods defined here:
|
| __init__(self, norm=None, cmap=None)
| Parameters
| ----------
| norm : :class:`matplotlib.colors.Normalize` instance
| The normalizing object which scales data, typically into the
| interval ``[0, 1]``.
| If *None*, *norm* defaults to a *colors.Normalize* object which
| initializes its scaling based on the first data processed.
| cmap : str or :class:`~matplotlib.colors.Colormap` instance
| The colormap used to map normalized data values to RGBA colors.
|
| add_checker(self, checker)
| Add an entry to a dictionary of boolean flags
| that are set to True when the mappable is changed.
|
| autoscale(self)
| Autoscale the scalar limits on the norm instance using the
| current array
|
| autoscale_None(self)
| Autoscale the scalar limits on the norm instance using the
| current array, changing only limits that are None
|
| changed(self)
| Call this whenever the mappable is changed to notify all the
| callbackSM listeners to the ''changed'' signal
|
| check_update(self, checker)
| If mappable has changed since the last check,
| return True; else return False
|
| get_array(self)
| Return the array
|
| get_clim(self)
| return the min, max of the color limits for image scaling
|
| get_cmap(self)
| return the colormap
|
| set_array(self, A)
| Set the image array from numpy array *A*.
|
| ..
| ACCEPTS: ndarray
|
| Parameters
| ----------
| A : ndarray
|
| set_clim(self, vmin=None, vmax=None)
| set the norm limits for image scaling; if *vmin* is a length2
| sequence, interpret it as ``(vmin, vmax)`` which is used to
| support setp
|
| ACCEPTS: a length 2 sequence of floats
|
| set_cmap(self, cmap)
| set the colormap for luminance data
|
| ACCEPTS: a colormap or registered colormap name
|
| set_norm(self, norm)
| Set the normalization instance.
|
| ..
| ACCEPTS: `~.Normalize`
|
| Parameters
| ----------
| norm : `~.Normalize`
|
| to_rgba(self, x, alpha=None, bytes=False, norm=True)
| Return a normalized rgba array corresponding to *x*.
|
| In the normal case, *x* is a 1-D or 2-D sequence of scalars, and
| the corresponding ndarray of rgba values will be returned,
| based on the norm and colormap set for this ScalarMappable.
|
| There is one special case, for handling images that are already
| rgb or rgba, such as might have been read from an image file.
| If *x* is an ndarray with 3 dimensions,
| and the last dimension is either 3 or 4, then it will be
| treated as an rgb or rgba array, and no mapping will be done.
| The array can be uint8, or it can be floating point with
| values in the 0-1 range; otherwise a ValueError will be raised.
| If it is a masked array, the mask will be ignored.
| If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
| will be used to fill in the transparency. If the last dimension
| is 4, the *alpha* kwarg is ignored; it does not
| replace the pre-existing alpha. A ValueError will be raised
| if the third dimension is other than 3 or 4.
|
| In either case, if *bytes* is *False* (default), the rgba
| array will be floats in the 0-1 range; if it is *True*,
| the returned rgba array will be uint8 in the 0 to 255 range.
|
| If norm is False, no normalization of the input data is
| performed, and it is assumed to be in the range (0-1).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)

FUNCTIONS
get_cmap(name=None, lut=None)
Get a colormap instance, defaulting to rc values if *name* is None.

Colormaps added with :func:`register_cmap` take precedence over
built-in colormaps.

If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be
returned.

If *lut* is not None it must be an integer giving the number of
entries desired in the lookup table, and *name* must be a standard
mpl colormap name.

register_cmap(name=None, cmap=None, data=None, lut=None)
Add a colormap to the set recognized by :func:`get_cmap`.

It can be used in two ways::

register_cmap(name=''swirly'', cmap=swirly_cmap)

register_cmap(name=''choppy'', data=choppydata, lut=128)

In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
instance. The *name* is optional; if absent, the name will
be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.

In the second case, the three arguments are passed to
the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
and the resulting colormap is registered.

revcmap(data)
Can only handle specification *data* in dictionary format.

DATA
Accent = <matplotlib.colors.ListedColormap object>
Accent_r = <matplotlib.colors.ListedColormap object>
Blues = <matplotlib.colors.LinearSegmentedColormap object>
Blues_r = <matplotlib.colors.LinearSegmentedColormap object>
BrBG = <matplotlib.colors.LinearSegmentedColormap object>
BrBG_r = <matplotlib.colors.LinearSegmentedColormap object>
BuGn = <matplotlib.colors.LinearSegmentedColormap object>
BuGn_r = <matplotlib.colors.LinearSegmentedColormap object>
BuPu = <matplotlib.colors.LinearSegmentedColormap object>
BuPu_r = <matplotlib.colors.LinearSegmentedColormap object>
CMRmap = <matplotlib.colors.LinearSegmentedColormap object>
CMRmap_r = <matplotlib.colors.LinearSegmentedColormap object>
Dark2 = <matplotlib.colors.ListedColormap object>
Dark2_r = <matplotlib.colors.ListedColormap object>
GnBu = <matplotlib.colors.LinearSegmentedColormap object>
GnBu_r = <matplotlib.colors.LinearSegmentedColormap object>
Greens = <matplotlib.colors.LinearSegmentedColormap object>
Greens_r = <matplotlib.colors.LinearSegmentedColormap object>
Greys = <matplotlib.colors.LinearSegmentedColormap object>
Greys_r = <matplotlib.colors.LinearSegmentedColormap object>
LUTSIZE = 256
OrRd = <matplotlib.colors.LinearSegmentedColormap object>
OrRd_r = <matplotlib.colors.LinearSegmentedColormap object>
Oranges = <matplotlib.colors.LinearSegmentedColormap object>
Oranges_r = <matplotlib.colors.LinearSegmentedColormap object>
PRGn = <matplotlib.colors.LinearSegmentedColormap object>
PRGn_r = <matplotlib.colors.LinearSegmentedColormap object>
Paired = <matplotlib.colors.ListedColormap object>
Paired_r = <matplotlib.colors.ListedColormap object>
Pastel1 = <matplotlib.colors.ListedColormap object>
Pastel1_r = <matplotlib.colors.ListedColormap object>
Pastel2 = <matplotlib.colors.ListedColormap object>
Pastel2_r = <matplotlib.colors.ListedColormap object>
PiYG = <matplotlib.colors.LinearSegmentedColormap object>
PiYG_r = <matplotlib.colors.LinearSegmentedColormap object>
PuBu = <matplotlib.colors.LinearSegmentedColormap object>
PuBuGn = <matplotlib.colors.LinearSegmentedColormap object>
PuBuGn_r = <matplotlib.colors.LinearSegmentedColormap object>
PuBu_r = <matplotlib.colors.LinearSegmentedColormap object>
PuOr = <matplotlib.colors.LinearSegmentedColormap object>
PuOr_r = <matplotlib.colors.LinearSegmentedColormap object>
PuRd = <matplotlib.colors.LinearSegmentedColormap object>
PuRd_r = <matplotlib.colors.LinearSegmentedColormap object>
Purples = <matplotlib.colors.LinearSegmentedColormap object>
Purples_r = <matplotlib.colors.LinearSegmentedColormap object>
RdBu = <matplotlib.colors.LinearSegmentedColormap object>
RdBu_r = <matplotlib.colors.LinearSegmentedColormap object>
RdGy = <matplotlib.colors.LinearSegmentedColormap object>
RdGy_r = <matplotlib.colors.LinearSegmentedColormap object>
RdPu = <matplotlib.colors.LinearSegmentedColormap object>
RdPu_r = <matplotlib.colors.LinearSegmentedColormap object>
RdYlBu = <matplotlib.colors.LinearSegmentedColormap object>
RdYlBu_r = <matplotlib.colors.LinearSegmentedColormap object>
RdYlGn = <matplotlib.colors.LinearSegmentedColormap object>
RdYlGn_r = <matplotlib.colors.LinearSegmentedColormap object>
Reds = <matplotlib.colors.LinearSegmentedColormap object>
Reds_r = <matplotlib.colors.LinearSegmentedColormap object>
Set1 = <matplotlib.colors.ListedColormap object>
Set1_r = <matplotlib.colors.ListedColormap object>
Set2 = <matplotlib.colors.ListedColormap object>
Set2_r = <matplotlib.colors.ListedColormap object>
Set3 = <matplotlib.colors.ListedColormap object>
Set3_r = <matplotlib.colors.ListedColormap object>
Spectral = <matplotlib.colors.LinearSegmentedColormap object>
Spectral_r = <matplotlib.colors.LinearSegmentedColormap object>
Vega10 = <matplotlib.colors.ListedColormap object>
Vega10_r = <matplotlib.colors.ListedColormap object>
Vega20 = <matplotlib.colors.ListedColormap object>
Vega20_r = <matplotlib.colors.ListedColormap object>
Vega20b = <matplotlib.colors.ListedColormap object>
Vega20b_r = <matplotlib.colors.ListedColormap object>
Vega20c = <matplotlib.colors.ListedColormap object>
Vega20c_r = <matplotlib.colors.ListedColormap object>
Wistia = <matplotlib.colors.LinearSegmentedColormap object>
Wistia_r = <matplotlib.colors.LinearSegmentedColormap object>
YlGn = <matplotlib.colors.LinearSegmentedColormap object>
YlGnBu = <matplotlib.colors.LinearSegmentedColormap object>
YlGnBu_r = <matplotlib.colors.LinearSegmentedColormap object>
YlGn_r = <matplotlib.colors.LinearSegmentedColormap object>
YlOrBr = <matplotlib.colors.LinearSegmentedColormap object>
YlOrBr_r = <matplotlib.colors.LinearSegmentedColormap object>
YlOrRd = <matplotlib.colors.LinearSegmentedColormap object>
YlOrRd_r = <matplotlib.colors.LinearSegmentedColormap object>
absolute_import = _Feature((2, 5, 0, ''alpha'', 1), (3, 0, 0, ''alpha'', 0...
afmhot = <matplotlib.colors.LinearSegmentedColormap object>
afmhot_r = <matplotlib.colors.LinearSegmentedColormap object>
autumn = <matplotlib.colors.LinearSegmentedColormap object>
autumn_r = <matplotlib.colors.LinearSegmentedColormap object>
binary = <matplotlib.colors.LinearSegmentedColormap object>
binary_r = <matplotlib.colors.LinearSegmentedColormap object>
bone = <matplotlib.colors.LinearSegmentedColormap object>
bone_r = <matplotlib.colors.LinearSegmentedColormap object>
brg = <matplotlib.colors.LinearSegmentedColormap object>
brg_r = <matplotlib.colors.LinearSegmentedColormap object>
bwr = <matplotlib.colors.LinearSegmentedColormap object>
bwr_r = <matplotlib.colors.LinearSegmentedColormap object>
cmap_d = {u''Spectral'': <matplotlib.colors.LinearSegmented...tlib.color...
cmapname = u''afmhot''
cmaps_listed = {''inferno'': <matplotlib.colors.ListedColormap object>, ...
cool = <matplotlib.colors.LinearSegmentedColormap object>
cool_r = <matplotlib.colors.LinearSegmentedColormap object>
coolwarm = <matplotlib.colors.LinearSegmentedColormap object>
coolwarm_r = <matplotlib.colors.LinearSegmentedColormap object>
copper = <matplotlib.colors.LinearSegmentedColormap object>
copper_r = <matplotlib.colors.LinearSegmentedColormap object>
cubehelix = <matplotlib.colors.LinearSegmentedColormap object>
cubehelix_r = <matplotlib.colors.LinearSegmentedColormap object>
datad = {u''Spectral'': ((0.6196078431372549, 0.0039215686...830>, u''red...
division = _Feature((2, 2, 0, ''alpha'', 2), (3, 0, 0, ''alpha'', 0), 8192...
flag = <matplotlib.colors.LinearSegmentedColormap object>
flag_r = <matplotlib.colors.LinearSegmentedColormap object>
gist_earth = <matplotlib.colors.LinearSegmentedColormap object>
gist_earth_r = <matplotlib.colors.LinearSegmentedColormap object>
gist_gray = <matplotlib.colors.LinearSegmentedColormap object>
gist_gray_r = <matplotlib.colors.LinearSegmentedColormap object>
gist_heat = <matplotlib.colors.LinearSegmentedColormap object>
gist_heat_r = <matplotlib.colors.LinearSegmentedColormap object>
gist_ncar = <matplotlib.colors.LinearSegmentedColormap object>
gist_ncar_r = <matplotlib.colors.LinearSegmentedColormap object>
gist_rainbow = <matplotlib.colors.LinearSegmentedColormap object>
gist_rainbow_r = <matplotlib.colors.LinearSegmentedColormap object>
gist_stern = <matplotlib.colors.LinearSegmentedColormap object>
gist_stern_r = <matplotlib.colors.LinearSegmentedColormap object>
gist_yarg = <matplotlib.colors.LinearSegmentedColormap object>
gist_yarg_r = <matplotlib.colors.LinearSegmentedColormap object>
gnuplot = <matplotlib.colors.LinearSegmentedColormap object>
gnuplot2 = <matplotlib.colors.LinearSegmentedColormap object>
gnuplot2_r = <matplotlib.colors.LinearSegmentedColormap object>
gnuplot_r = <matplotlib.colors.LinearSegmentedColormap object>
gray = <matplotlib.colors.LinearSegmentedColormap object>
gray_r = <matplotlib.colors.LinearSegmentedColormap object>
hot = <matplotlib.colors.LinearSegmentedColormap object>
hot_r = <matplotlib.colors.LinearSegmentedColormap object>
hsv = <matplotlib.colors.LinearSegmentedColormap object>
hsv_r = <matplotlib.colors.LinearSegmentedColormap object>
inferno = <matplotlib.colors.ListedColormap object>
inferno_r = <matplotlib.colors.ListedColormap object>
jet = <matplotlib.colors.LinearSegmentedColormap object>
jet_r = <matplotlib.colors.LinearSegmentedColormap object>
magma = <matplotlib.colors.ListedColormap object>
magma_r = <matplotlib.colors.ListedColormap object>
nipy_spectral = <matplotlib.colors.LinearSegmentedColormap object>
nipy_spectral_r = <matplotlib.colors.LinearSegmentedColormap object>
ocean = <matplotlib.colors.LinearSegmentedColormap object>
ocean_r = <matplotlib.colors.LinearSegmentedColormap object>
pink = <matplotlib.colors.LinearSegmentedColormap object>
pink_r = <matplotlib.colors.LinearSegmentedColormap object>
plasma = <matplotlib.colors.ListedColormap object>
plasma_r = <matplotlib.colors.ListedColormap object>
print_function = _Feature((2, 6, 0, ''alpha'', 2), (3, 0, 0, ''alpha'', 0)...
prism = <matplotlib.colors.LinearSegmentedColormap object>
prism_r = <matplotlib.colors.LinearSegmentedColormap object>
rainbow = <matplotlib.colors.LinearSegmentedColormap object>
rainbow_r = <matplotlib.colors.LinearSegmentedColormap object>
seismic = <matplotlib.colors.LinearSegmentedColormap object>
seismic_r = <matplotlib.colors.LinearSegmentedColormap object>
spectral = <matplotlib.colors.LinearSegmentedColormap object>
spectral_r = <matplotlib.colors.LinearSegmentedColormap object>
spring = <matplotlib.colors.LinearSegmentedColormap object>
spring_r = <matplotlib.colors.LinearSegmentedColormap object>
summer = <matplotlib.colors.LinearSegmentedColormap object>
summer_r = <matplotlib.colors.LinearSegmentedColormap object>
tab10 = <matplotlib.colors.ListedColormap object>
tab10_r = <matplotlib.colors.ListedColormap object>
tab20 = <matplotlib.colors.ListedColormap object>
tab20_r = <matplotlib.colors.ListedColormap object>
tab20b = <matplotlib.colors.ListedColormap object>
tab20b_r = <matplotlib.colors.ListedColormap object>
tab20c = <matplotlib.colors.ListedColormap object>
tab20c_r = <matplotlib.colors.ListedColormap object>
terrain = <matplotlib.colors.LinearSegmentedColormap object>
terrain_r = <matplotlib.colors.LinearSegmentedColormap object>
unicode_literals = _Feature((2, 6, 0, ''alpha'', 2), (3, 0, 0, ''alpha'', ...
viridis = <matplotlib.colors.ListedColormap object>
viridis_r = <matplotlib.colors.ListedColormap object>
winter = <matplotlib.colors.LinearSegmentedColormap object>
winter_r = <matplotlib.colors.LinearSegmentedColormap object>

Jupyterlab / Notebook 中的交互式 matplotlib 图(使用 ipympl 的 %matplotlib 小部件)仅工作一次然后消失

Jupyterlab / Notebook 中的交互式 matplotlib 图(使用 ipympl 的 %matplotlib 小部件)仅工作一次然后消失

如何解决Jupyterlab / Notebook 中的交互式 matplotlib 图(使用 ipympl 的 %matplotlib 小部件)仅工作一次然后消失?

我再次尝试在 Jupyter Notebooks 中为我的学生使用交互式 matplotlib 图。我的计划是使用 JupyterLab,因为普通的 Notebook 界面在学生中不太受欢迎。这是一个两芯 MWE 笔记本:

import numpy as np
%matplotlib widget
import matplotlib.pyplot as plt

下一个单元格:

plt.figure(1)
x = np.arange(100)
y = x*x
plt.plot(x,y)
plt.show()

当我运行这些单元格时,我确实得到了一个交互式 Matplotlib 图。但是当我第二次运行第二个单元格时,绘图窗口消失而没有警告或错误,只有在我在第二个单元格之前重新运行第一个单元格时才会返回。经典笔记本界面显示相同的行为,删除 plt.show()plt.figure() 也没有区别。

我在 venv 环境中的 Windows 10 计算机上本地运行 Jupyter 服务器,安装了以下版本:

Python           : 3.8.2
ipympl           : 0.7.0

jupyter core     : 4.7.1
jupyter-notebook : 6.3.0
qtconsole        : not installed
ipython          : 7.23.1
ipykernel        : 5.5.4
jupyter client   : 6.1.12
jupyter lab      : 3.0.14
nbconvert        : 6.0.7
ipywidgets       : 7.6.3
nbformat         : 5.1.3
traitlets        : 5.0.5

在我的非专业人士看来,启动期间的消息似乎没问题:

[I 2021-05-12 10:10:48.065 LabApp] JupyterLab extension loaded from d:\envs\pyfda_38\lib\site-packages\jupyterlab
[I 2021-05-12 10:10:48.065 LabApp] JupyterLab application directory is D:\envs\pyfda_38\share\jupyter\lab
[I 2021-05-12 10:10:48.069 ServerApp] jupyterlab | extension was successfully loaded.
[I 2021-05-12 10:10:48.488 ServerApp] nbclassic | extension was successfully loaded.
[I 2021-05-12 10:10:48.489 ServerApp] Serving notebooks from local directory: D:\Daten\xxx
[I 2021-05-12 10:10:48.489 ServerApp] Jupyter Server 1.6.4 is running at:
[I 2021-05-12 10:10:48.489 ServerApp] http://localhost:8888/lab?token=xxxx

我得到的唯一(可能)相关警告是

[W 2021-05-12 10:10:55.256 LabApp] Could not determine jupyterlab build status without nodejs 

是我做错了什么,还是 ipympl 的交互图还不够成熟,无法进行 BYOD 课程?

解决方法

它在每次通过将魔术命令移动到第二个单元格来激活 matplotlib 交互式支持时起作用:

%matplotlib widget
plt.figure(1)
x = np.arange(100)
y = x*x
plt.plot(x,y)
plt.show()

matplotlib - 数据框 - 如何在 matplotlib 的背景上有真实的地图

matplotlib - 数据框 - 如何在 matplotlib 的背景上有真实的地图

geopandas 提供了一个 API,让这一切变得非常简单。这是一个示例,其中地图放大到非洲大陆:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import geopandas

df = pd.DataFrame(
   {'Latitude': np.random.uniform(-20,10,100),'Longitude': np.random.uniform(40,20,100)})

gdf = geopandas.GeoDataFrame(
    df,geometry=geopandas.points_from_xy(df.Longitude,df.Latitude))

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))

ax = world[world.continent == 'Africa'].plot(color='white',edgecolor='black')

# We can now plot our ``GeoDataFrame``.
gdf.plot(ax=ax,color='red')

plt.show()

结果:

关于numpy 与 matplotlib 的应用过程numpy和matplotlib关系的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Eclipse 中的 Matplotlib.axes 与 matplotlib.pyplot.axes、Help on module matplotlib.cm in matplotlib:、Jupyterlab / Notebook 中的交互式 matplotlib 图(使用 ipympl 的 %matplotlib 小部件)仅工作一次然后消失、matplotlib - 数据框 - 如何在 matplotlib 的背景上有真实的地图等相关知识的信息别忘了在本站进行查找喔。

本文标签: