python 之可视化图表

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
In [2]:

fig=plt.figure(figsize=(10,5))

In [3]:

type(fig)
Out[3]:
matplotlib.figure.Figure
In [4]:

ax1=fig.add_subplot(1,2,1)
In [5]:

ax1.figure
Out[5]:

In [6]:

ax2=fig.add_subplot(1,2,2)
In [7]:

ax2.figure
Out[7]:

In [8]:

fig1,axes=plt.subplots(nrows=2,ncols=2,figsize=(10,10))

In [9]:

type(axes)
Out[9]:
numpy.ndarray
In [10]:

axes[0,0]
Out[10]:
<matplotlib.axes._subplots.AxesSubplot at 0x95ed828>
In [11]:

#解决中文乱码问题
In [12]:

plt.rcParams[“font.sans-serif”]=“SimHei”
plt.rcParams[“axes.unicode_minus”]=False
In [13]:

df1=pd.DataFrame(np.random.rand(30,3),columns=list(“abc”)).cumsum()
In [14]:

df1[“a”].plot.line(color=“r”,linestyle="–",marker="^",alpha=0.5)
Out[14]:
<matplotlib.axes._subplots.AxesSubplot at 0x95c4fd0>

In [15]:

df1.plot.line(colormap=“summer”,linestyle="–",marker=".",grid=True)
Out[15]:
<matplotlib.axes._subplots.AxesSubplot at 0x9761198>

In [16]:

df1.plot(kind=“line”,y=[“a”,“b”],marker="+",linestyle="-",color=[“r”,“b”])
Out[16]:
<matplotlib.axes._subplots.AxesSubplot at 0x97e5ba8>

In [17]:

fig1,axes=plt.subplots(2,1,figsize=(6,10))
df1.plot(kind=“line”,colormap=“spring”,marker=".",
linestyle="–",grid=True,alpha=0.8,ax=axes[0])
Out[17]:
<matplotlib.axes._subplots.AxesSubplot at 0x985d0b8>

In [18]:

df1.plot.line(color=[“r”,“k”,“b”],alpha=0.5,ax=axes[1])
Out[18]:
<matplotlib.axes._subplots.AxesSubplot at 0x987dc18>
In [19]:

axes[1].figure
Out[19]:

In [20]:

fig1,axes=plt.subplots(1,2,figsize=(10,5))
df1=pd.DataFrame(np.random.rand(10,3),columns=list(“abc”)).cumsum()
df2=pd.DataFrame(np.random.rand(10,3),columns=list(“abc”)).cumsum()
axes[0].plot(df1,linestyle="–",marker="^")
axes[1].plot(df1,".–",df2,“±”)

Out[20]:
[<matplotlib.lines.Line2D at 0xaabce48>,
<matplotlib.lines.Line2D at 0xaaed208>,
<matplotlib.lines.Line2D at 0xaaed358>,
<matplotlib.lines.Line2D at 0xaaed4a8>,
<matplotlib.lines.Line2D at 0xaaedba8>,
<matplotlib.lines.Line2D at 0xaaedcf8>]

In [21]:

fig1,ax=plt.subplots(1,1,figsize=(6,6))
df1=pd.DataFrame(np.random.randn(50,3),columns=[“x1”,“x2”,“x3”]).cumsum()
df1.plot(linestyle="–",color=[“r”,“b”,“k”],marker=" ? ? ?",ax=ax)
Out[21]:
<matplotlib.axes._subplots.AxesSubplot at 0xaaff198>

In [22]:

ax.set_title(“时间序列图”,fontsize=20)
ax.set_xlabel(“时间”,fontsize=10)
ax.set_ylabel(“价格”,fontsize=10)
ax.set_xlim([0,60])
ax.set_ylim([-5,17])
h1=range(0,60,5)
ax.set_xticks(h1)
ax.set_xticklabels(list(“abcdefghigk”))
v1=range(-5,16,1)
ax.set_yticks(v1)
ax.set_yticklabels("%.2f"%i for i in v1)
ax.grid()
ax.legend(loc=“upper left”)
ax.figure
Out[22]:

In [23]:

ax.text(10,11,“Hello!”,fontsize=10,color=“r”,rotation=45,va=“bottom”)
ax.figure
fig1.suptitle(“这就是我的画布”,fontsize=25)
ax.figure
Out[23]:

In [24]:

help(fig1.suptitle)
Help on method suptitle in module matplotlib.figure:

suptitle(t, **kwargs) method of matplotlib.figure.Figure instance
Add a centered title to the figure.

Parameters
----------
t : str
    The title text.

x : float, default 0.5
    The x location of the text in figure coordinates.

y : float, default 0.98
    The y location of the text in figure coordinates.

horizontalalignment, ha : {'center', 'left', right'}, default: 'center'
    The horizontal alignment of the text relative to (*x*, *y*).

verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, default: 'top'
    The vertical alignment of the text relative to (*x*, *y*).

fontsize, size : default: :rc:`figure.titlesize`
    The font size of the text. See `.Text.set_size` for possible
    values.

fontweight, weight : default: :rc:`figure.titleweight`
    The font weight of the text. See `.Text.set_weight` for possible
    values.


Returns
-------
    text
        The `.Text` instance of the title.


Other Parameters
----------------
fontproperties : None or dict, optional
    A dict of font properties. If *fontproperties* is given the
    default values for font size and weight are taken from the
    `FontProperties` defaults. :rc:`figure.titlesize` and
    :rc:`figure.titleweight` are ignored in this case.

**kwargs
    Additional kwargs are :class:`matplotlib.text.Text` properties.


Examples
--------

>>> fig.suptitle('This is the figure title', fontsize=12)

In [25]:

dir(ax)
Out[25]:
[‘class’,
delattr’,
dict’,
dir’,
doc’,
eq’,
format’,
ge’,
getattribute’,
getstate’,
gt’,
hash’,
init’,
init_subclass’,
le’,
lt’,
module’,
ne’,
new’,
reduce’,
reduce_ex’,
repr’,
setattr’,
setstate’,
sizeof’,
str’,
subclasshook’,
weakref’,
‘_add_text’,
‘_adjustable’,
‘_agg_filter’,
‘_alpha’,
‘_anchor’,
‘_animated’,
‘_aspect’,
‘_autoscaleXon’,
‘_autoscaleYon’,
‘_autotitlepos’,
‘_axes’,
‘_axes_class’,
‘_axes_locator’,
‘_axisbelow’,
‘_cachedRenderer’,
‘_clipon’,
‘_clippath’,
‘_connected’,
‘_contains’,
‘_current_image’,
‘_facecolor’,
‘_frameon’,
‘_gci’,
‘_gen_axes_patch’,
‘_gen_axes_spines’,
‘_get_axis_list’,
‘_get_lines’,
‘_get_patches_for_fill’,
‘_get_view’,
‘_gid’,
‘_gridOn’,
‘_hold’,
‘_in_layout’,
‘_init_axis’,
‘_label’,
‘_layoutbox’,
‘_left_title’,
‘_make_twin_axes’,
‘_mouseover’,
‘_mouseover_set’,
‘_navigate’,
‘_navigate_mode’,
‘_oid’,
‘_on_units_changed’,
‘_originalPosition’,
‘_path_effects’,
‘_pcolorargs’,
‘_picker’,
‘_position’,
‘_poslayoutbox’,
‘_process_unit_info’,
‘_prop_order’,
‘_propobservers’,
‘_quiver_units’,
‘_rasterization_zorder’,
‘_rasterized’,
‘_remove_legend’,
‘_remove_method’,
‘_right_title’,
‘_sci’,
‘_set_artist_props’,
‘_set_gc_clip’,
‘_set_lim_and_transforms’,
‘_set_position’,
‘_set_title_offset_trans’,
‘_set_view’,
‘_set_view_from_bbox’,
‘_shared_x_axes’,
‘_shared_y_axes’,
‘_sharex’,
‘_sharey’,
‘_sketch’,
‘_snap’,
‘_stale’,
‘_sticky_edges’,
‘_subplotspec’,
‘_tight’,
‘_transform’,
‘_transformSet’,
‘_twinned_axes’,
‘_update_image_limits’,
‘_update_line_limits’,
‘_update_patch_limits’,
‘_update_title_position’,
‘_update_transScale’,
‘_url’,
‘_use_sticky_edges’,
‘_validate_converted_limits’,
‘_visible’,
‘_xaxis_transform’,
‘_xcid’,
‘_xmargin’,
‘_yaxis_transform’,
‘_ycid’,
ymargin’,
‘acorr’,
‘add_artist’,
‘add_callback’,
‘add_child_axes’,
‘add_collection’,
‘add_container’,
‘add_image’,
‘add_line’,
‘add_patch’,
‘add_table’,
‘aname’,
‘angle_spectrum’,
‘annotate’,
‘apply_aspect’,
‘arrow’,
‘artists’,
‘autoscale’,
‘autoscale_view’,
‘axes’,
‘axhline’,
‘axhspan’,
‘axis’,
‘axison’,
‘axvline’,
‘axvspan’,
‘bar’,
‘barbs’,
‘barh’,
‘bbox’,
‘boxplot’,
‘broken_barh’,
‘bxp’,
‘callbacks’,
‘can_pan’,
‘can_zoom’,
‘change_geometry’,
‘child_axes’,
‘cla’,
‘clabel’,
‘clear’,
‘clipbox’,
‘cohere’,
‘colNum’,
‘collections’,
‘containers’,
‘contains’,
‘contains_point’,
‘contour’,
‘contourf’,
‘convert_xunits’,
‘convert_yunits’,
‘csd’,
‘dataLim’,
‘drag_pan’,
‘draw’,
‘draw_artist’,
‘end_pan’,
‘errorbar’,
‘eventplot’,
‘eventson’,
‘figbox’,
‘figure’,
‘fill’,
‘fill_between’,
‘fill_betweenx’,
‘findobj’,
‘fmt_xdata’,
‘fmt_ydata’,
‘format_coord’,
‘format_cursor_data’,
‘format_xdata’,
‘format_ydata’,
‘get_adjustable’,
‘get_agg_filter’,
‘get_alpha’,
‘get_anchor’,
‘get_animated’,
‘get_aspect’,
‘get_autoscale_on’,
‘get_autoscalex_on’,
‘get_autoscaley_on’,
‘get_axes_locator’,
‘get_axisbelow’,
‘get_children’,
‘get_clip_box’,
‘get_clip_on’,
‘get_clip_path’,
‘get_contains’,
‘get_cursor_data’,
‘get_data_ratio’,
‘get_data_ratio_log’,
‘get_default_bbox_extra_artists’,
‘get_facecolor’,
‘get_fc’,
‘get_figure’,
‘get_frame_on’,
‘get_geometry’,
‘get_gid’,
‘get_gridspec’,
‘get_images’,
‘get_in_layout’,
‘get_label’,
‘get_legend’,
‘get_legend_handles_labels’,
‘get_lines’,
‘get_navigate’,
‘get_navigate_mode’,
‘get_path_effects’,
‘get_picker’,
‘get_position’,
‘get_rasterization_zorder’,
‘get_rasterized’,
‘get_renderer_cache’,
‘get_shared_x_axes’,
‘get_shared_y_axes’,
‘get_sketch_params’,
‘get_snap’,
‘get_subplotspec’,
‘get_tightbbox’,
‘get_title’,
‘get_transform’,
‘get_transformed_clip_path_and_affine’,
‘get_url’,
‘get_visible’,
‘get_window_extent’,
‘get_xaxis’,
‘get_xaxis_text1_transform’,
‘get_xaxis_text2_transform’,
‘get_xaxis_transform’,
‘get_xbound’,
‘get_xgridlines’,
‘get_xlabel’,
‘get_xlim’,
‘get_xmajorticklabels’,
‘get_xminorticklabels’,
‘get_xscale’,
‘get_xticklabels’,
‘get_xticklines’,
‘get_xticks’,
‘get_yaxis’,
‘get_yaxis_text1_transform’,
‘get_yaxis_text2_transform’,
‘get_yaxis_transform’,
‘get_ybound’,
‘get_ygridlines’,
‘get_ylabel’,
‘get_ylim’,
‘get_ymajorticklabels’,
‘get_yminorticklabels’,
‘get_yscale’,
‘get_yticklabels’,
‘get_yticklines’,
‘get_yticks’,
‘get_zorder’,
‘grid’,
‘has_data’,
‘have_units’,
‘hexbin’,
‘hist’,
‘hist2d’,
‘hitlist’,
‘hlines’,
‘ignore_existing_data_limits’,
‘images’,
‘imshow’,
‘in_axes’,
‘indicate_inset’,
‘indicate_inset_zoom’,
‘inset_axes’,
‘invert_xaxis’,
‘invert_yaxis’,
‘is_figure_set’,
‘is_first_col’,
‘is_first_row’,
‘is_last_col’,
‘is_last_row’,
‘is_transform_set’,
‘label_outer’,
‘legend’,
'legend
’,
‘lines’,
‘locator_params’,
‘loglog’,
‘magnitude_spectrum’,
‘margins’,
‘matshow’,
‘minorticks_off’,
‘minorticks_on’,
‘mouseover’,
‘mouseover_set’,
‘name’,
‘numCols’,
‘numRows’,
‘patch’,
‘patches’,
‘pchanged’,
‘pcolor’,
‘pcolorfast’,
‘pcolormesh’,
‘phase_spectrum’,
‘pick’,
‘pickable’,
‘pie’,
‘plot’,
‘plot_date’,
‘properties’,
‘psd’,
‘quiver’,
‘quiverkey’,
‘redraw_in_frame’,
‘relim’,
‘remove’,
‘remove_callback’,
‘reset_position’,
‘rowNum’,
‘scatter’,
‘semilogx’,
‘semilogy’,
‘set’,
‘set_adjustable’,
‘set_agg_filter’,
‘set_alpha’,
‘set_anchor’,
‘set_animated’,
‘set_aspect’,
‘set_autoscale_on’,
‘set_autoscalex_on’,
‘set_autoscaley_on’,
‘set_axes_locator’,
‘set_axis_off’,
‘set_axis_on’,
‘set_axisbelow’,
‘set_clip_box’,
‘set_clip_on’,
‘set_clip_path’,
‘set_contains’,
‘set_facecolor’,
‘set_fc’,
‘set_figure’,
‘set_frame_on’,
‘set_gid’,
‘set_in_layout’,
‘set_label’,
‘set_navigate’,
‘set_navigate_mode’,
‘set_path_effects’,
‘set_picker’,
‘set_position’,
‘set_prop_cycle’,
‘set_rasterization_zorder’,
‘set_rasterized’,
‘set_sketch_params’,
‘set_snap’,
‘set_subplotspec’,
‘set_title’,
‘set_transform’,
‘set_url’,
‘set_visible’,
‘set_xbound’,
‘set_xlabel’,
‘set_xlim’,
‘set_xmargin’,
‘set_xscale’,
‘set_xticklabels’,
‘set_xticks’,
‘set_ybound’,
‘set_ylabel’,
‘set_ylim’,
‘set_ymargin’,
‘set_yscale’,
‘set_yticklabels’,
‘set_yticks’,
‘set_zorder’,
‘specgram’,
‘spines’,
‘spy’,
‘stackplot’,
‘stale’,
‘stale_callback’,
‘start_pan’,
‘stem’,
‘step’,
‘sticky_edges’,
‘streamplot’,
‘table’,
‘tables’,
‘text’,
‘texts’,
‘tick_params’,
‘ticklabel_format’,
‘title’,
‘titleOffsetTrans’,
‘transAxes’,
‘transData’,
‘transLimits’,
‘transScale’,
‘tricontour’,
‘tricontourf’,
‘tripcolor’,
‘triplot’,
‘twinx’,
‘twiny’,
‘update’,
‘update_datalim’,
‘update_datalim_bounds’,
‘update_from’,
‘update_params’,
‘use_sticky_edges’,
‘viewLim’,
‘violin’,
‘violinplot’,
‘vlines’,
‘xaxis’,
‘xaxis_date’,
‘xaxis_inverted’,
‘xcorr’,
‘yaxis’,
‘yaxis_date’,
‘yaxis_inverted’,
‘zorder’]
In [26]:

df1.columns
Out[26]:
Index([‘x1’, ‘x2’, ‘x3’], dtype=‘object’)
In [27]:

df1.shape
Out[27]:
(50, 3)
In [28]:

df1.info()
<class ‘pandas.core.frame.DataFrame’>
RangeIndex: 50 entries, 0 to 49
Data columns (total 3 columns):
x1 50 non-null float64
x2 50 non-null float64
x3 50 non-null float64
dtypes: float64(3)
memory usage: 1.2 KB
In [29]:

df1.plot(style={“x1”:“ro–”,“x2”:“b±-”,“x3”:“k.-”})
Out[29]:
<matplotlib.axes._subplots.AxesSubplot at 0xad1c470>

In [30]:

data1=pd.DataFrame({“x”:np.random.rand(100),
“l”:np.random.choice([“a”,“b”,“c”]),
“y”:np.random.rand(100)})
In [31]:

fig1,ax=plt.subplots(1,1,figsize=(10,5))

In [32]:

data1.plot(x=“l”,y=“x”,ax=ax)
Out[32]:
<matplotlib.axes._subplots.AxesSubplot at 0xadb1400>
In [33]:

ax.get_xticks()
Out[33]:
array([ 0., 20., 40., 60., 80., 100.])
In [34]:

data1[“l”][0:101:10]
Out[34]:
0 b
10 b
20 b
30 b
40 b
50 b
60 b
70 b
80 b
90 b
Name: l, dtype: object
In [35]:

ax.set_xticks(range(0,100,10))
ax.set_xticklabels(data1[“l”][0:101:10])
ax.figure
Out[35]:

In [36]:

ax.figure
Out[36]:

In [37]:

#条形图
In [38]:

fig,axes=plt.subplots(5,1,figsize=(8,20))
df1=pd.DataFrame(np.random.randint(4,9,(10,3)),columns=[“x1”,“x2”,“x3”])

In [39]:

fig,axes=plt.subplots(5,1,figsize=(8,20))
df1=pd.DataFrame(np.random.randint(4,9,(10,3)),columns=[“x1”,“x2”,“x3”])
df1[“x1”].plot.bar(color=“b”,alpha=0.7,grid=True,ax=axes[0])
axes[0].set_title(“单变量纵向条形图”)
df1[“x1”].plot.barh(edgecolor="#00FFFF",facecolor=“r”,
alpha=0.5,width=0.4,ax=axes[1])
axes[1].set_title(“单变量横向条形图”)
df1.plot.bar(colormap=“winter”,ax=axes[2])
axes[2].set_title(“多变量柱形图”)
df1.plot.bar(stacked=True,ax=axes[3])
df1[“x1”].plot.bar(color=“r”,ax=axes[4])
df1[“x2”]=-df1[“x2”]
df1[“x2”].plot.bar(color=“b”,ax=axes[4])
for i,j in zip(df1.index,df1[“x1”].values):
axes[4].text(i,j,"%.2f"%j,va=“top”,ha=“center”,color=“k”)
for i,j in zip(df1.index,df1[“x2”].values):
axes[4].text(i,j-0.5,"%.2f"%-j,va=“bottom”,ha=“center”,color=“k”)
axes[0].figure
Out[39]:

In [40]:

df1
Out[40]:
x1 x2 x3
0 5 -7 8
1 7 -4 5
2 6 -4 6
3 8 -7 8
4 8 -6 7
5 4 -5 4
6 8 -7 5
7 5 -7 6
8 4 -4 4
9 8 -6 4
In [41]:

help(plt.bar)
Help on function bar in module matplotlib.pyplot:

bar(x, height, width=0.8, bottom=None, *, align=‘center’, data=None, **kwargs)
Make a bar plot.

The bars are positioned at *x* with the given *align*\ment. Their
dimensions are given by *width* and *height*. The vertical baseline
is *bottom* (default 0).

Each of *x*, *height*, *width*, and *bottom* may either be a scalar
applying to all bars, or it may be a sequence of length N providing a
separate value for each bar.

Parameters
----------
x : sequence of scalars
    The x coordinates of the bars. See also *align* for the
    alignment of the bars to the coordinates.

height : scalar or sequence of scalars
    The height(s) of the bars.

width : scalar or array-like, optional
    The width(s) of the bars (default: 0.8).

bottom : scalar or array-like, optional
    The y coordinate(s) of the bars bases (default: 0).

align : {'center', 'edge'}, optional, default: 'center'
    Alignment of the bars to the *x* coordinates:

    - 'center': Center the base on the *x* positions.
    - 'edge': Align the left edges of the bars with the *x* positions.

    To align the bars on the right edge pass a negative *width* and
    ``align='edge'``.

Returns
-------
container : `.BarContainer`
    Container with all the bars and optionally errorbars.

Other Parameters
----------------
color : scalar or array-like, optional
    The colors of the bar faces.

edgecolor : scalar or array-like, optional
    The colors of the bar edges.

linewidth : scalar or array-like, optional
    Width of the bar edge(s). If 0, don't draw edges.

tick_label : string or array-like, optional
    The tick labels of the bars.
    Default: None (Use default numeric labels.)

xerr, yerr : scalar or array-like of shape(N,) or shape(2,N), optional
    If not *None*, add horizontal / vertical errorbars to the bar tips.
    The values are +/- sizes relative to the data:

    - scalar: symmetric +/- values for all bars
    - shape(N,): symmetric +/- values for each bar
    - shape(2,N): Separate - and + values for each bar. First row
        contains the lower errors, the second row contains the
        upper errors.
    - *None*: No errorbar. (Default)

    See :doc:`/gallery/statistics/errorbar_features`
    for an example on the usage of ``xerr`` and ``yerr``.

ecolor : scalar or array-like, optional, default: 'black'
    The line color of the errorbars.

capsize : scalar, optional
   The length of the error bar caps in points.
   Default: None, which will take the value from
   :rc:`errorbar.capsize`.

error_kw : dict, optional
    Dictionary of kwargs to be passed to the `~.Axes.errorbar`
    method. Values of *ecolor* or *capsize* defined here take
    precedence over the independent kwargs.

log : bool, optional, default: False
    If *True*, set the y-axis to be log scale.

orientation : {'vertical',  'horizontal'}, optional
    *This is for internal use only.* Please use `barh` for
    horizontal bar plots. Default: 'vertical'.

See also
--------
barh: Plot a horizontal bar plot.

Notes
-----
The optional arguments *color*, *edgecolor*, *linewidth*,
*xerr*, and *yerr* can be either scalars or sequences of
length equal to the number of bars.  This enables you to use
bar as the basis for stacked bar charts, or candlestick plots.
Detail: *xerr* and *yerr* are passed directly to
:meth:`errorbar`, so they can also have shape 2xN for
independent specification of lower and upper errors.

Other optional kwargs:

  agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array 
  alpha: float or None
  animated: bool
  antialiased: unknown
  capstyle: {'butt', 'round', 'projecting'}
  clip_box: `.Bbox`
  clip_on: bool
  clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None] 
  color: color
  contains: callable
  edgecolor: color or None or 'auto'
  facecolor: color or None
  figure: `.Figure`
  fill: bool
  gid: str
  hatch: {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
  in_layout: bool
  joinstyle: {'miter', 'round', 'bevel'}
  label: object
  linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  linewidth: float or None for default 
  path_effects: `.AbstractPathEffect`
  picker: None or bool or float or callable
  rasterized: bool or None
  sketch_params: (scale: float, length: float, randomness: float) 
  snap: bool or None
  transform: `.Transform`
  url: str
  visible: bool
  zorder: float

.. note::
    In addition to the above described arguments, this function can take a
    **data** keyword argument. If such a **data** argument is given, the
    following arguments are replaced by **data[<arg>]**:

    * All arguments with the following names: 'bottom', 'color', 'ecolor', 'edgecolor', 'height', 'left', 'linewidth', 'tick_label', 'width', 'x', 'xerr', 'y', 'yerr'.
    * All positional arguments.

    Objects passed as **data** must support item access (``data[<arg>]``) and
    membership test (``<arg> in data``).

In [42]:

df1.info()
<class ‘pandas.core.frame.DataFrame’>
RangeIndex: 10 entries, 0 to 9
Data columns (total 3 columns):
x1 10 non-null int32
x2 10 non-null int32
x3 10 non-null int32
dtypes: int32(3)
memory usage: 200.0 bytes
In [43]:

df1[“x2”]=-df1[“x2”]
df1.plot.area(colormap=“summer”,stacked=True)
Out[43]:
<matplotlib.axes._subplots.AxesSubplot at 0xb54e8d0>

In [44]:

fig,axes=plt.subplots(4,1,figsize=(8,15))
x=np.linspace(0,9.42,100)
y1=np.sin(x)
y2=np.cos(x)
axes[0].plot(x,y1,label=“sinx”)
axes[0].plot(x,y2,label=“cosx”)
axes[0].legend()
axes[1].fill(x,y1,“r”,alpha=0.5,label=“sinx”)
axes[2].fill(x,y2,“b”,alpha=0.5,label=“cosx”)
axes[3].fill_between(x,y1,y2)
Out[44]:
<matplotlib.collections.PolyCollection at 0xb693f28>

In [45]:

fig,axes=plt.subplots(1,2,figsize=(15,7))
df1=pd.DataFrame(np.random.rand(5,3),columns=[“x1”,“x2”,“x3”],index=list(“abcde”))
df1[“x1”].plot.pie(colors=[“yellow”,“red”,“black”,“pink”,“green”],ax=axes[0])
df1[“x2”].plot.pie(explode=[0.1,0,0,0,0],radius=1,
ax=axes[1],
autopct="%.2f%%",
textprops={“fontsize”:25},
labeldistance=1.1,
colormap=“summer”
)
axes[1].set_ylabel(None)
axes[1].set_title(“饼形图”,fontsize=40)
Out[45]:
Text(0.5, 1.0, ‘饼形图’)

In [46]:

fig,axes=plt.subplots(3,1,figsize=(6,18))
df1=pd.DataFrame({“a”:np.random.normal(5,2,1000),
“b”:np.random.normal(7,2,1000),
“c”: np.random.normal(9,2,1000),
“t”: np.random.randint(1,4,1000)})
df1.plot.hist(ax=axes[0])
df1[“a”].plot.hist(ax=axes[1],density=True,color=“b”,alpha=0.3,bins=50)
df1[“a”].plot(kind=“kde”,ax=axes[1])
Out[46]:
<matplotlib.axes._subplots.AxesSubplot at 0xb7ea630>

In [47]:

axes=df1.hist(column=[“a”,“b”,“c”],by=“t”)
axes[0,0].legend()
No handles with labels found to put in legend.
Out[47]:
<matplotlib.legend.Legend at 0xbf3feb8>

In [48]:

fig1,axes=plt.subplots(4,1,figsize=(6,18))
df1=pd.DataFrame({“x”:np.random.rand(1000),
“y”:np.random.rand(1000),
“z”:np.random.rand(1000)})
axes[0].scatter(df1[“x”],df1[“y”],color=“r”)
axes[0].grid()
axes[1].scatter(df1[“x”],df1[“y”],color=“r”,alpha=0.5)
axes[1].scatter(df1[“x”],df1[“z”],color=“g”,alpha=0.2)
temp=axes[2].scatter(df1[“x”],df1[“y”],c=df1[“y”],cmap=“Greens”)
fig1.colorbar(temp,ax=axes[2])
df1.plot.scatter(x=“x”,y=“y”,c=df1[“y”],cmap=“summer”,ax=axes[3],colorbar=True)
axes[1].grid()

axes[1].legend()
Out[48]:
<matplotlib.legend.Legend at 0xe3c9be0>

In [49]:

pd.plotting.scatter_matrix(df1,figsize=(10,10),marker="+",color=“r”)
Out[49]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E71D860>,
<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E76D1D0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E4AA780>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E4CFCF8>,
<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E5012B0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E525828>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E54FDA0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E57F390>,
<matplotlib.axes._subplots.AxesSubplot object at 0x000000000E57F3C8>]],
dtype=object)

In [50]:

fig,axes = plt.subplots(2,1,figsize=(10,20))
df1 = pd.DataFrame({“x1”:np.random.normal(0,1,1000),
“x2”:np.random.normal(0,1.5,1000),
“x3”:np.random.normal(1,1,1000),
“x4”:np.random.normal(1,2,1000)})
color=dict(boxes=“b”,medians=“r”,whiskers=“yellow”,caps=“k”)
df1.plot.box(color=color,ax=axes[0])
df1[[“x1”,“x2”]].plot.box(color=color,vert=False,
ax=axes[1],positions=[1,3],grid=True,sym=“r+”)
Out[50]:
<matplotlib.axes._subplots.AxesSubplot at 0xee0a5c0>

In [51]:

fig,ax = plt.subplots(1,1,figsize=(10,6))
f=df1.boxplot(sym=“o”,
showbox=True,
showmeans=True,
showcaps=True,
patch_artist=True,
return_type=“dict”,
notch=True,ax=ax)

In [52]:

f[“boxes”]
Out[52]:
[<matplotlib.patches.PathPatch at 0xf2ffcf8>,
<matplotlib.patches.PathPatch at 0xf311748>,
<matplotlib.patches.PathPatch at 0xf328160>,
<matplotlib.patches.PathPatch at 0xf330b38>]
In [53]:

f[“boxes”][0]
Out[53]:
<matplotlib.patches.PathPatch at 0xf2ffcf8>
In [54]:

f[“boxes”][0].set(color=“r”,linewidth=2)
Out[54]:
[None, None]
In [55]:

ax.figure
Out[55]:

In [56]:

df = pd.DataFrame(np.random.rand(10,2), columns=[‘x’, ‘y’] )
df[‘type1’] = pd.Series([‘A’,‘A’,‘A’,‘A’,‘A’,‘B’,‘B’,‘B’,‘B’,‘B’])
df[‘type2’] = pd.Series([‘T1’,‘T2’,‘T1’,‘T2’,
‘T1’,‘T2’,‘T1’,‘T2’,‘T1’,‘T2’])
In [57]:

df.boxplot(by=“type1”,patch_artist=True)
df.boxplot(by=[“type1”,“type2”])
Out[57]:
array([<matplotlib.axes._subplots.AxesSubplot object at 0x000000000F384EB8>,
<matplotlib.axes._subplots.AxesSubplot object at 0x000000000F63D550>],
dtype=object)

In [58]:

fig=plt.figure(figsize=(8,8))
ax=fig.add_subplot(111,polar=True)
labels=[“语文”,“数学”,“英语”,“物理”,“化学”,“生物”]
zhangsan=np.array([90,80,30,50,60,70])
lisi=np.array([20,80,70,65,76,90])
angles=np.linspace(0,2np.pi,6,endpoint=False)

zhangsan=np.concatenate((zhangsan,[zhangsan[0]]))
lisi=np.concatenate((lisi,[lisi[0]]))
angles=np.concatenate((angles,[angles[0]]))
ax.plot(angles,zhangsan,“ro–”,label=“张三”)
ax.plot(angles,lisi,“bo–”,label=“李四”)
ax.fill(angles,zhangsan,facecolor=“r”,alpha=0.2)
ax.fill(angles,lisi,facecolor=“b”,alpha=0.2)
angles1=angles
180/np.pi
ax.set_thetagrids(angles1,labels)
ax.set_title(“分数雷达图”)
ax.grid(True)
ax.legend(loc=“upper left”)
ax.legend(loc=(-0.2,0))
Out[58]:
<matplotlib.legend.Legend at 0xf9afda0>

In [59]:

.savefig(“mypicture.jpg”)
fig.savefig(“mypicture.jpg”)
In [60]:

xv=np.linspace(-10,10,10)
yv=np.linspace(-10,10,10)
x,y=np.meshgrid(xv,yv)
In [61]:

x=x.ravel()
y=y.ravel()
In [62]:

len(x)
Out[62]:
100
In [63]:

xc=x[(x2+y2)0.5<=10]
yc=y[(x
2+y**2)**0.5<=10]
In [64]:

r(xc,yc,c=yc,cmap=“summer”,s=2)
fig,ax=plt.subplots(1,1,figsize=(8,8))
ax.scatter(xc,yc,c=yc,cmap=“summer”,s=2)
Out[64]:
<matplotlib.collections.PathCollection at 0x101dc780>

In [ ]:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值