本文整理匯總了Python中matplotlib.pyplot方法的典型用法代碼示例。如果您正苦於以下問題:Python matplotlib.pyplot方法的具體用法?Python matplotlib.pyplot怎麽用?Python matplotlib.pyplot使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類matplotlib
的用法示例。
在下文中一共展示了matplotlib.pyplot方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: cortex_cmap_plot_2D
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def cortex_cmap_plot_2D(the_map, zs, cmap, vmin=None, vmax=None, axes=None, triangulation=None):
'''
cortex_cmap_plot_2D(map, zs, cmap, axes) plots the given cortical map values zs on the given
axes using the given given color map and yields the resulting polygon collection object.
cortex_cmap_plot_2D(map, zs, cmap) uses matplotlib.pyplot.gca() for the axes.
The following options may be passed:
* triangulation (None) may specify the triangularion object for the mesh if it has already
been created; otherwise it is generated fresh.
* axes (None) specify the axes on which to plot; if None, then matplotlib.pyplot.gca() is
used. If Ellipsis, then a tuple (triangulation, z, cmap) is returned; to recreate the plot,
one would call:
axes.tripcolor(triangulation, z, cmap, shading='gouraud', vmin=vmin, vmax=vmax)
* vmin (default: None) specifies the minimum value for scaling the property when one is passed
as the color option. None means to use the min value of the property.
* vmax (default: None) specifies the maximum value for scaling the property when one is passed
as the color option. None means to use the max value of the property.
'''
if triangulation is None:
triangulation = matplotlib.tri.Triangulation(the_map.coordinates[0], the_map.coordinates[1],
triangles=the_map.tess.indexed_faces.T)
if axes is Ellipsis: return (triangulation, zs, cmap)
return axes.tripcolor(triangulation, zs, cmap=cmap, shading='gouraud', vmin=vmin, vmax=vmax)
示例2: task_3_IQR
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def task_3_IQR(flight_data):
plot=plt.boxplot(flight_data['Price'],patch_artist=True)
for median in plot['medians']:
median.set(color='#fc0004', linewidth=2)
for flier in plot['fliers']:
flier.set(marker='+', color='#e7298a')
for whisker in plot['whiskers']:
whisker.set(color='#7570b3', linewidth=2)
for cap in plot['caps']:
cap.set(color='#7570b3', linewidth=2)
for box in plot['boxes']:
box.set(color='#7570b3', linewidth=2)
box.set(facecolor='#1b9e77')
plt.matplotlib.pyplot.savefig('task_3_iqr.png')
clean_data=[]
for index,row in flight_data.loc[flight_data['Price'].isin(plot['fliers'][0].get_ydata())].iterrows():
clean_data.append([row['Price'],row['Date_of_Flight']])
return pd.DataFrame(clean_data, columns=['Price', 'Date_of_Flight'])
示例3: plot_coordinates
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def plot_coordinates(coordinates, plot_path, markers, label_names, fig_num):
matplotlib.use('svg')
import matplotlib.pyplot as plt
plt.figure(fig_num)
for i in range(len(markers) - 1):
plt.scatter(x=coordinates[markers[i]:markers[i + 1], 0],
y=coordinates[markers[i]:markers[i + 1], 1],
marker=plot_markers[i % len(plot_markers)],
c=colors[i % len(colors)],
label=label_names[i], alpha=0.75)
plt.legend(loc='upper right', fontsize='x-large')
plt.axis('off')
plt.savefig(fname=plot_path, format="svg", bbox_inches='tight', transparent=True)
plt.close()
示例4: assert_is_valid_plot_return_object
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def assert_is_valid_plot_return_object(objs): # pragma: no cover
import matplotlib.pyplot as plt
if isinstance(objs, (pd.Series, np.ndarray)):
for el in objs.ravel():
msg = (
"one of 'objs' is not a matplotlib Axes instance, "
"type encountered {}".format(repr(type(el).__name__))
)
assert isinstance(el, (plt.Axes, dict)), msg
else:
msg = (
"objs is neither an ndarray of Artist instances nor a single "
"ArtistArtist instance, tuple, or dict, 'objs' is a {}".format(
repr(type(objs).__name__))
)
assert isinstance(objs, (plt.Artist, tuple, dict)), msg
示例5: plot_images
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def plot_images(ax, images, shape, color = False):
# finally save to file
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# flip 0 to 1
images = 1.0 - images
images = reshape_and_tile_images(images, shape, n_cols=len(images))
if color:
from matplotlib import cm
plt.imshow(images, cmap=cm.Greys_r, interpolation='nearest')
else:
plt.imshow(images, cmap='Greys')
ax.axis('off')
示例6: test_plot_irf
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def test_plot_irf(self):
import matplotlib.pyplot as plt
self.irf.plot()
plt.close('all')
self.irf.plot(plot_stderr=False)
plt.close('all')
self.irf.plot(impulse=0, response=1)
plt.close('all')
self.irf.plot(impulse=0)
plt.close('all')
self.irf.plot(response=0)
plt.close('all')
self.irf.plot(orth=True)
plt.close('all')
self.irf.plot(impulse=0, response=1, orth=True)
close_plots()
示例7: save_plot
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def save_plot(niters, loss, args):
print('Saving training loss-iteration figure...')
try:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
name = 'Train-{}_hs-{}_lr-{}_bs-{}'.format(args.train_file, args.hs,
args.lr, args.batch_size)
plt.title(name)
plt.plot(niters, loss)
plt.xlabel('iteration')
plt.ylabel('loss')
plt.savefig(name + '.jpg')
print('{} saved!'.format(name + '.jpg'))
except ImportError:
print('matplotlib not installed and no figure is saved.')
示例8: initialize_pyplot
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def initialize_pyplot(self):
"""
Call me before use!
[Supposed to be done inside already running server process]
"""
if not self.ready:
from multiprocessing import Pipe
self.out_pipe, self.in_pipe = Pipe()
if self.plt is None:
import matplotlib
matplotlib.use(self.plt_backend, force=True)
import matplotlib.pyplot as plt
self.plt = plt
self.ready = True
示例9: visualize_waveform
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def visualize_waveform(audio_signal, ch=0, do_mono=False, x_axis='time', **kwargs):
"""
Wrapper around `librosa.display.waveplot` for usage with AudioSignals.
Args:
audio_signal (AudioSignal): AudioSignal to plot
ch (int, optional): Which channel to plot. Defaults to 0.
do_mono (bool, optional): Make the AudioSignal mono. Defaults to False.
x_axis (str, optional): x_axis argument to librosa.display.waveplot. Defaults to 'time'.
kwargs: Additional keyword arguments to librosa.display.waveplot.
"""
import librosa.display
import matplotlib.pyplot as plt
if do_mono:
audio_signal = audio_signal.to_mono(overwrite=False)
data = np.asfortranarray(audio_signal.audio_data[ch])
librosa.display.waveplot(data, sr=audio_signal.sample_rate, x_axis=x_axis, **kwargs)
plt.ylabel('Amplitude')
示例10: draw
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def draw():
"""
Redraw the current figure.
This is used in interactive mode to update a figure that
has been altered using one or more plot object method calls;
it is not needed if figure modification is done entirely
with pyplot functions, if a sequence of modifications ends
with a pyplot function, or if matplotlib is in non-interactive
mode and the sequence of modifications ends with :func:`show` or
:func:`savefig`.
A more object-oriented alternative, given any
:class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
was created using a :mod:`~matplotlib.pyplot` function, is::
fig.canvas.draw()
"""
get_current_fig_manager().canvas.draw()
示例11: xlabel
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def xlabel(s, *args, **kwargs):
"""
Set the *x* axis label of the current axis.
Default override is::
override = {
'fontsize' : 'small',
'verticalalignment' : 'top',
'horizontalalignment' : 'center'
}
.. seealso::
:func:`~matplotlib.pyplot.text`
For information on how override and the optional args work
"""
l = gca().set_xlabel(s, *args, **kwargs)
draw_if_interactive()
return l
示例12: polar
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def polar(*args, **kwargs):
"""
Make a polar plot.
call signature::
polar(theta, r, **kwargs)
Multiple *theta*, *r* arguments are supported, with format
strings, as in :func:`~matplotlib.pyplot.plot`.
"""
ax = gca(polar=True)
ret = ax.plot(*args, **kwargs)
draw_if_interactive()
return ret
示例13: activate_matplotlib
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def activate_matplotlib(backend):
"""Activate the given backend and set interactive to True."""
import matplotlib
matplotlib.interactive(True)
# Matplotlib had a bug where even switch_backend could not force
# the rcParam to update. This needs to be set *before* the module
# magic of switch_backend().
matplotlib.rcParams['backend'] = backend
import matplotlib.pyplot
matplotlib.pyplot.switch_backend(backend)
# This must be imported last in the matplotlib series, after
# backend/interactivity choices have been made
import matplotlib.pylab as pylab
pylab.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
示例14: plot_f
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def plot_f(f, filenm='test_function.eps'):
# only for 2D functions
import matplotlib.pyplot as plt
import matplotlib
font = {'size': 20}
matplotlib.rc('font', **font)
delta = 0.005
x = np.arange(0.0, 1.0, delta)
y = np.arange(0.0, 1.0, delta)
nx = len(x)
X, Y = np.meshgrid(x, y)
xx = np.array((X.ravel(), Y.ravel())).T
yy = f(xx)
plt.figure()
plt.contourf(X, Y, yy.reshape(nx, nx), levels=np.linspace(yy.min(), yy.max(), 40))
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.colorbar()
plt.scatter(f.argmax[0], f.argmax[1], s=180, color='k', marker='+')
plt.savefig(filenm)
示例15: Cont
# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import pyplot [as 別名]
def Cont(imG):
#This is meant to create plots similar to the ones from
#https://www.bu.edu/blazars/VLBA_GLAST/3c454.html
#for the visual comparison
import matplotlib.pyplot as plt
plt.figure()
Z = np.reshape(imG.imvec,(imG.xdim,imG.ydim))
pov = imG.xdim*imG.psize
pov_mas = pov/(RADPERUAS*1.e3)
Zmax = np.amax(Z)
print(Zmax)
levels = np.array((-0.00125*Zmax,0.00125*Zmax,0.0025*Zmax, 0.005*Zmax, 0.01*Zmax,
0.02*Zmax, 0.04*Zmax, 0.08*Zmax, 0.16*Zmax, 0.32*Zmax, 0.64*Zmax))
CS = plt.contour(Z, levels,
origin='lower',
linewidths=2,
extent=(-pov_mas/2., pov_mas/2., -pov_mas/2., pov_mas/2.))
plt.show()