自学内容网 自学内容网

Python酷库之旅-第三方库Pandas(132)

目录

一、用法精讲

591、pandas.DataFrame.plot方法

591-1、语法

591-2、参数

591-3、功能

591-4、返回值

591-5、说明

591-6、用法

591-6-1、数据准备

591-6-2、代码示例

591-6-3、结果输出

592、pandas.DataFrame.plot.area方法

592-1、语法

592-2、参数

592-3、功能

592-4、返回值

592-5、说明

592-6、用法

592-6-1、数据准备

592-6-2、代码示例

592-6-3、结果输出

593、pandas.DataFrame.plot.bar方法

593-1、语法

593-2、参数

593-3、功能

593-4、返回值

593-5、说明

593-6、用法

593-6-1、数据准备

593-6-2、代码示例

593-6-3、结果输出

594、pandas.DataFrame.plot.barh方法

594-1、语法

594-2、参数

594-3、功能

594-4、返回值

594-5、说明

594-6、用法

594-6-1、数据准备

594-6-2、代码示例

594-6-3、结果输出

595、pandas.DataFrame.plot.box方法

595-1、语法

595-2、参数

595-3、功能

595-4、返回值

595-5、说明

595-6、用法

595-6-1、数据准备

595-6-2、代码示例

595-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页
​​​​​​​

一、用法精讲

591、pandas.DataFrame.plot方法
591-1、语法
# 591、pandas.DataFrame.plot方法
pandas.DataFrame.plot(*args, **kwargs)
Make plots of Series or DataFrame.

Uses the backend specified by the option plotting.backend. By default, matplotlib is used.

Parameters:
dataSeries or DataFrame
The object for which the method is called.

xlabel or position, default None
Only used if data is a DataFrame.

ylabel, position or list of label, positions, default None
Allows plotting of one column versus another. Only used if data is a DataFrame.

kindstr
The kind of plot to produce:

‘line’ : line plot (default)

‘bar’ : vertical bar plot

‘barh’ : horizontal bar plot

‘hist’ : histogram

‘box’ : boxplot

‘kde’ : Kernel Density Estimation plot

‘density’ : same as ‘kde’

‘area’ : area plot

‘pie’ : pie plot

‘scatter’ : scatter plot (DataFrame only)

‘hexbin’ : hexbin plot (DataFrame only)

axmatplotlib axes object, default None
An axes of the current figure.

subplotsbool or sequence of iterables, default False
Whether to group columns into subplots:

False : No subplots will be used

True : Make separate subplots for each column.

sequence of iterables of column labels: Create a subplot for each group of columns. For example [(‘a’, ‘c’), (‘b’, ‘d’)] will create 2 subplots: one with columns ‘a’ and ‘c’, and one with columns ‘b’ and ‘d’. Remaining columns that aren’t specified will be plotted in additional subplots (one per column).

New in version 1.5.0.

sharexbool, default True if ax is None else False
In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in; Be aware, that passing in both an ax and sharex=True will alter all x axis labels for all axis in a figure.

shareybool, default False
In case subplots=True, share y axis and set some y axis labels to invisible.

layouttuple, optional
(rows, columns) for the layout of subplots.

figsizea tuple (width, height) in inches
Size of a figure object.

use_indexbool, default True
Use index as ticks for x axis.

titlestr or list
Title to use for the plot. If a string is passed, print the string at the top of the figure. If a list is passed and subplots is True, print each item in the list above the corresponding subplot.

gridbool, default None (matlab style default)
Axis grid lines.

legendbool or {‘reverse’}
Place legend on axis subplots.

stylelist or dict
The matplotlib line style per column.

logxbool or ‘sym’, default False
Use log scaling or symlog scaling on x axis.

logybool or ‘sym’ default False
Use log scaling or symlog scaling on y axis.

loglogbool or ‘sym’, default False
Use log scaling or symlog scaling on both x and y axes.

xtickssequence
Values to use for the xticks.

ytickssequence
Values to use for the yticks.

xlim2-tuple/list
Set the x limits of the current axes.

ylim2-tuple/list
Set the y limits of the current axes.

xlabellabel, optional
Name to use for the xlabel on x-axis. Default uses index name as xlabel, or the x-column name for planar plots.

Changed in version 2.0.0: Now applicable to histograms.

ylabellabel, optional
Name to use for the ylabel on y-axis. Default will show no ylabel, or the y-column name for planar plots.

Changed in version 2.0.0: Now applicable to histograms.

rotfloat, default None
Rotation for ticks (xticks for vertical, yticks for horizontal plots).

fontsizefloat, default None
Font size for xticks and yticks.

colormapstr or matplotlib colormap object, default None
Colormap to select colors from. If string, load colormap with that name from matplotlib.

colorbarbool, optional
If True, plot colorbar (only relevant for ‘scatter’ and ‘hexbin’ plots).

positionfloat
Specify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center).

tablebool, Series or DataFrame, default False
If True, draw a table using the data in the DataFrame and the data will be transposed to meet matplotlib’s default layout. If a Series or DataFrame is passed, use passed data to draw a table.

yerrDataFrame, Series, array-like, dict and str
See Plotting with Error Bars for detail.

xerrDataFrame, Series, array-like, dict and str
Equivalent to yerr.

stackedbool, default False in line and bar plots, and True in area plot
If True, create stacked plot.

secondary_ybool or sequence, default False
Whether to plot on the secondary y-axis if a list/tuple, which columns to plot on secondary y-axis.

mark_rightbool, default True
When using a secondary_y axis, automatically mark the column labels with “(right)” in the legend.

include_boolbool, default is False
If True, boolean values can be plotted.

backendstr, default None
Backend to use instead of the backend specified in the option plotting.backend. For instance, ‘matplotlib’. Alternatively, to specify the plotting.backend for the whole session, set pd.options.plotting.backend.

**kwargs
Options to pass to matplotlib plotting method.

Returns:
matplotlib.axes.Axes
or numpy.ndarray of them
If the backend is not the default matplotlib one, the return value will be the object returned by the backend.

Notes

See matplotlib documentation online for more on this subject

If kind = ‘bar’ or ‘barh’, you can specify relative alignments for bar plot layout by position keyword. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center).
591-2、参数

591-2-1、data(必须)DataFrame,表示待绘制的数据,必须是一个DataFrame对象。

591-2-2、x(可选,默认值为None)label or position,用作x轴值的列标签或列的位置。

591-2-3、y(可选,默认值为None)label、position or list of label/position,表示列标签或列的位置,用于绘制y轴,如果没有指定,则会绘制所有数值列。

591-2-4、kind(可选,默认值为'line')字符串,指定图的类型,可以是以下几种:

  • 'line':折线图(默认值)
  • 'bar':垂直条形图
  • 'barh':水平条形图
  • 'hist':直方图
  • 'box':箱线图
  • 'kde':Kernel Density Estimation图
  • 'density':同'kde'
  • 'area':面积图
  • 'pie':饼图
  • 'scatter'散点图(需要指定x和y)
  • 'hexbin':六边形图(需要指定x和y)

591-2-5、ax(可选,默认值为None)matplotlib axes object,表示要在其上绘制的axes对象。

591-2-6、subplots(可选,默认值为False)布尔值,是否为每一列绘制一个子图。

591-2-7、sharex(可选,默认值为False)布尔值,如果subplots=True,子图是否共享x轴。

591-2-8、sharey(可选,默认值为False)布尔值,如果subplots=True,子图是否共享y轴。

591-2-9、layout(可选,默认值为None)元组,表示子图的布局,(行, 列)格式。

591-2-10、figsize(可选,默认值为None)元组,图的尺寸,(宽, 高)格式。

591-2-11、use_index(可选,默认值为True)布尔值,是否将DataFrame的索引用作x轴标签。

591-2-12、title(必须)字符串或列表,表示图的标题。

591-2-13、grid(可选,默认值为None)布尔值,是否显示网格。

591-2-14、legend(可选,默认值为True)布尔值,是否显示图例。

591-2-15、style(可选,默认值为None)列表或字典,样式字符串或dict对象,用于定制线条样式。

591-2-16、logx(可选,默认值为False)布尔值,是否使用x轴的对数刻度。

591-2-17、logy(可选,默认值为False)布尔值,是否使用y轴的对数刻度。

591-2-18、loglog(可选,默认值为False)布尔值,是否对x轴和y轴都使用对数刻度。

591-2-19、xticks(可选,默认值为None)sequence,自定义x轴刻度。

591-2-20、yticks(可选,默认值为None)sequence,自定义y轴刻度。

591-2-21、xlim(可选,默认值为None)2-tuple,x轴的限制(min, max)。

591-2-22、ylim(可选,默认值为None)2-tuple,y轴的限制(min, max)。

591-2-23、rot(可选,默认值为None)整数,x轴标签的旋转角度。

591-2-24、fontsize(可选,默认值为None)整数,x轴和y轴标签的字体大小。

591-2-25、colormap(可选,默认值为None)字符串或可迭代对象,颜色映射或colormap。

591-2-26、position(可选,默认值为0.5)浮点数,条的位置(仅用于条形图)。

591-2-27、table(可选,默认值为False)bool、DataFrame or Series,如果为True,将数据添加到图表中作为数据表,如果是DataFrame,则绘制该表的数据;如果是Series,则绘制该Series的数据。

591-2-28、yerr(必须)str or DataFrame or array,y轴的误差条。

591-2-29、xerr(必须)str or DataFrame or array,x轴的误差条。

591-2-30、stacked(可选,默认值为False)布尔值,如果为True,堆积条形图。

591-2-31、sort_columns(可选,默认值为False)布尔值,是否按列标签排序。

591-3、功能

        用来绘制基于DataFrame数据的各种类型的图,它是一个高度便利的函数,结合了pandas和matplotlib的功能,可以迅速生成高质量的可视化图表,便于数据分析和展示。

591-4、返回值

        如果subplots=False,返回matplotlib.axes.Axes对象;如果subplots=True,返回numpy.ndarray数组,其中每个元素都是matplotlib.axes.Axes对象。

591-5、说明

        无

591-6、用法
591-6-1、数据准备
591-6-2、代码示例
# 591、pandas.DataFrame.plot方法
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt  # 需要导入 matplotlib
# 创建示例数据
df = pd.DataFrame({
    'A': np.random.randn(1000),
    'B': np.random.randn(1000),
    'C': np.random.randn(1000),
    'D': np.random.randn(1000)
})
# 绘制折线图
fig, ax = plt.subplots()  # 创建新的图和轴对象
df.plot(x='A', y='B', kind='line', ax=ax, title='Line Plot')
plt.show()  # 显示折线图
# 绘制散点图
fig, ax = plt.subplots()
df.plot(x='A', y='B', kind='scatter', ax=ax, title='Scatter Plot')
plt.show()  # 显示散点图
591-6-3、结果输出
# 591、pandas.DataFrame.plot方法
见图1
见图2

图1(类似):

图2(类似):

 

592、pandas.DataFrame.plot.area方法
592-1、语法
# 592、pandas.DataFrame.plot.area方法
pandas.DataFrame.plot.area(x=None, y=None, stacked=True, **kwargs)
Draw a stacked area plot.

An area plot displays quantitative data visually. This function wraps the matplotlib area function.

Parameters:
x
label or position, optional
Coordinates for the X axis. By default uses the index.

y
label or position, optional
Column to plot. By default uses all columns.

stacked
bool, default True
Area plots are stacked by default. Set to False to create a unstacked plot.

**kwargs
Additional keyword arguments are documented in DataFrame.plot().

Returns:
matplotlib.axes.Axes or numpy.ndarray
Area plot, or array of area plots if subplots is True.
592-2、参数

592-2-1、x(可选,默认值为None)字符串或序列,指定用于绘制x轴的数据列,如果没有提供,将根据DataFrame的索引来绘图。

592-2-2、y(可选,默认值为None)字符串、序列或列表,指定用于绘制y轴的数据列,如果为None,所有列将被用于绘图。

592-2-3、stacked(可选,默认值为True)布尔值,如果为True,绘制堆叠面积图;如果为False,绘制重叠面积图。

592-2-4、**kwargs(可选)字典,其他绘图参数,通常用于设置线条颜色、透明度、标签、标题等,例如color、alpha、label、title等。

592-3、功能

        用于创建面积图,可以有效显示不同类别数据随时间的趋势变化,以及它们之间的相对大小关系。

592-3-1、堆叠面积图:通过设置stacked=True,可以清晰地展示各个类别的相对大小。

592-3​​​​​​​-2、重叠面积图:通过设置stacked=False,可以观察不同类别之间的重叠情况。

592-4、返回值

        返回一个Matplotlib的Axes对象,这使得用户可以对图形进行进一步的定制和保存操作。

592-5、说明

        无

592-6、用法
592-6-1、数据准备
592-6-2、代码示例
# 592、pandas.DataFrame.plot.area方法
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

# 配置字体,确保中文字符正常显示
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号 '-' 显示问题
# 示例数据
data = {'A': [1, 2, 3, 4], 'B': [2, 3, 4, 5], 'C': [3, 4, 1, 2]}
df = pd.DataFrame(data)
# 绘制堆叠面积图
df.plot.area(stacked=True)
plt.title("堆叠面积图")
plt.xlabel("时间")
plt.ylabel("值")
plt.show()
592-6-3、结果输出
# 592、pandas.DataFrame.plot.area方法
见图3

图3:

 

593、pandas.DataFrame.plot.bar方法
593-1、语法
# 593、pandas.DataFrame.plot.bar方法
pandas.DataFrame.plot.bar(x=None, y=None, **kwargs)
Vertical bar plot.

A bar plot is a plot that presents categorical data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, and the other axis represents a measured value.

Parameters:
x
label or position, optional
Allows plotting of one column versus another. If not specified, the index of the DataFrame is used.

y
label or position, optional
Allows plotting of one column versus another. If not specified, all numerical columns are used.

color
str, array-like, or dict, optional
The color for each of the DataFrame’s columns. Possible values are:

A single color string referred to by name, RGB or RGBA code,
for instance ‘red’ or ‘#a98d19’.

A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each column recursively. For instance [‘green’,’yellow’] each column’s bar will be filled in green or yellow, alternatively. If there is only a single column to be plotted, then only the first color from the color list will be used.

A dict of the form {column namecolor}, so that each column will be
colored accordingly. For example, if your columns are called a and b, then passing {‘a’: ‘green’, ‘b’: ‘red’} will color bars for column a in green and bars for column b in red.

**kwargs
Additional keyword arguments are documented in DataFrame.plot().

Returns:
matplotlib.axes.Axes or np.ndarray of them
An ndarray is returned with one matplotlib.axes.Axes per column when subplots=True.
593-2、参数

593-2-1、x(可选,默认值为None)字符串或序列,指定用于绘制x轴的数据列,如果没有提供,将根据DataFrame的索引来绘图。

593-2-2、y(可选,默认值为None)字符串、序列或列表,指定用于绘制y轴的数据列,如果为None,将根据DataFrame的其他列进行绘图。

593-2-3、**kwargs(可选)字典,其他绘图参数,例如label、title、xlabel、ylabel等,用于设置图例标签、标题和坐标轴标签等。

593-3、功能

        用于创建条形图,适合于展示分类数据的比较,常用来:

593-3-1、比较不同类别之间的数量或值。

593-3-2、显示时间序列数据的变化情况,如果将时间作为类别,则可以观察某一时间段内不同类别的表现。

593-4、返回值

        返回一个Matplotlib的Axes对象,这允许用户对图形进行进一步的定制和保存。

593-5、说明

        无

593-6、用法
593-6-1、数据准备
593-6-2、代码示例
# 593、pandas.DataFrame.plot.bar方法
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

# 配置字体,确保中文字符正常显示
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号 '-' 显示问题
# 示例数据
data = {'类别': ['A', 'B', 'C', 'D'], '值': [3, 7, 5, 8]}
df = pd.DataFrame(data)
# 绘制条形图
df.plot.bar(x='类别', y='值', color='purple', alpha=0.7)
plt.title("条形图示例")
plt.xlabel("类别")
plt.ylabel("值")
plt.grid(axis='y')
plt.show()
593-6-3、结果输出
# 593、pandas.DataFrame.plot.bar方法
见图4

图4:

 

594、pandas.DataFrame.plot.barh方法
594-1、语法
# 594、pandas.DataFrame.plot.barh方法
pandas.DataFrame.plot.barh(x=None, y=None, **kwargs)
Make a horizontal bar plot.

A horizontal bar plot is a plot that presents quantitative data with rectangular bars with lengths proportional to the values that they represent. A bar plot shows comparisons among discrete categories. One axis of the plot shows the specific categories being compared, and the other axis represents a measured value.

Parameters:
x
label or position, optional
Allows plotting of one column versus another. If not specified, the index of the DataFrame is used.

y
label or position, optional
Allows plotting of one column versus another. If not specified, all numerical columns are used.

color
str, array-like, or dict, optional
The color for each of the DataFrame’s columns. Possible values are:

A single color string referred to by name, RGB or RGBA code,
for instance ‘red’ or ‘#a98d19’.

A sequence of color strings referred to by name, RGB or RGBA
code, which will be used for each column recursively. For instance [‘green’,’yellow’] each column’s bar will be filled in green or yellow, alternatively. If there is only a single column to be plotted, then only the first color from the color list will be used.

A dict of the form {column namecolor}, so that each column will be
colored accordingly. For example, if your columns are called a and b, then passing {‘a’: ‘green’, ‘b’: ‘red’} will color bars for column a in green and bars for column b in red.

**kwargs
Additional keyword arguments are documented in DataFrame.plot().

Returns:
matplotlib.axes.Axes or np.ndarray of them
An ndarray is returned with one matplotlib.axes.Axes per column when subplots=True.
594-2、参数

594-2-1、x(可选,默认值为None)字符串或序列,指定用于绘制x轴的数据列,如果没有提供,将根据DataFrame的索引来绘图。

594-2-2、y(可选,默认值为None)字符串、序列或列表,指定用于绘制y轴的数据列,如果为None,将根据DataFrame的其他列进行绘图。

594-2-3、**kwargs(可选)字典,其他绘图参数,例如label、title、xlabel、ylabel等,用于设置图例标签、标题和坐标轴标签等。

594-3、功能

        用于创建水平条形图,适合于展示分类数据的比较,常用来:

594-3-1、比较不同类别之间的数量或值,尤其在类别名称较长时,更易于展示。

594-3-2、显示时间序列数据的变化情况,如果将时间作为类别,则可以观察某一时间段内不同类别的表现。

594-4、返回值

        返回一个Matplotlib的Axes对象,允许用户对图形进行进一步的定制和保存。

594-5、说明

        无

594-6、用法
594-6-1、数据准备
594-6-2、代码示例
# 594、pandas.DataFrame.plot.barh方法
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
# 配置字体,确保中文字符正常显示
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号 '-' 显示问题
# 示例数据
data = {'类别': ['A', 'B', 'C', 'D'], '值': [3, 7, 5, 8]}
df = pd.DataFrame(data)
# 绘制水平条形图
df.plot.barh(x='类别', y='值', color='green', alpha=0.7)
plt.title("水平条形图示例")
plt.xlabel("值")
plt.ylabel("类别")
plt.grid(axis='x')
plt.show()
594-6-3、结果输出
# 594、pandas.DataFrame.plot.barh方法
见图5

图5:

 

595、pandas.DataFrame.plot.box方法
595-1、语法
# 595、pandas.DataFrame.plot.box方法
pandas.DataFrame.plot.box(by=None, **kwargs)
Make a box plot of the DataFrame columns.

A box plot is a method for graphically depicting groups of numerical data through their quartiles. The box extends from the Q1 to Q3 quartile values of the data, with a line at the median (Q2). The whiskers extend from the edges of box to show the range of the data. The position of the whiskers is set by default to 1.5*IQR (IQR = Q3 - Q1) from the edges of the box. Outlier points are those past the end of the whiskers.

For further details see Wikipedia’s entry for boxplot.

A consideration when using this chart is that the box and the whiskers can overlap, which is very common when plotting small sets of data.

Parameters:
bystr or sequence
Column in the DataFrame to group by.

Changed in version 1.4.0: Previously, by is silently ignore and makes no groupings

**kwargs
Additional keywords are documented in DataFrame.plot().

Returns:
matplotlib.axes.Axes
or numpy.ndarray of them.
595-2、参数

595-2-1、by(可选,默认值为None)字符串或序列,用于分组的列或列名,传入后,箱线图将根据该列的不同值进行分组绘制,能够对比不同类别的数据分布。

595-2-2、**kwargs(可选)字典,其他绘图参数,可用于定制图形外观,例如:

  • color: 设置箱体和须的颜色。
  • grid: bool,是否显示网格线,默认False。
  • fontsize: 设置坐标轴的字体大小。
  • title: 图标题。
  • xlabel / ylabel: 坐标轴标签。
  • widths: float,设置箱体的宽度
595-3、功能

        用于创建箱线图,适用于以下场景:

595-3-1、数据分布: 可视化连续数据的五数概括,包括最小值、第一四分位数、中位数、第三四分位数和最大值。

595-3-2、异常值检测: 通过箱子外的点来识别异常值。

595-3​​​​​​​-3、比较组间差异: 利用by参数,能够比较不同组(类别)之间的数据分布差异。

595-4、返回值

        返回一个Matplotlib的Axes对象,允许用户对图形进行进一步的定制和保存。

595-5、说明

        无

595-6、用法
595-6-1、数据准备
595-6-2、代码示例
# 595、pandas.DataFrame.plot.box方法
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
# 配置字体,确保中文字符正常显示
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决负号 '-' 显示问题
# 示例数据
data = {
    '类别': ['A', 'A', 'A', 'B', 'B', 'B'],
    '值': [1, 2, 5, 5, 6, 7]
}
df = pd.DataFrame(data)
# 绘制箱线图
df.plot.box(by='类别', grid=True, title="箱线图示例", fontsize=12)
plt.ylabel("值")
plt.show()
595-6-3、结果输出
# 595、pandas.DataFrame.plot.box方法
见图6

图6:

 

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页

原文地址:https://blog.csdn.net/ygb_1024/article/details/142635069

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!