Matplotlib 简明教程

Matplotlib - Bar Graphs

bar plot 是一种图形化数据表示,其中使用矩形条或列表示不同的类别。每条条形的高度与它所代表的值相对应。

A bar plot is a graphical representation of data where rectangular bars or columns are used to represent different categories. The height of each bar corresponds to the value it represents.

水平轴(x 轴)通常表示需要比较的类别或组,而垂直轴(y 轴)表示与每个类别关联的值或数量。每条条形都从轴开始,并且水平或垂直延伸,具体取决于图表的朝向。

The horizontal axis (x-axis) typically represents the categories or groups being compared, while the vertical axis (y-axis) represents the values or quantities associated with each category. Each bar starts at the axis and extends horizontally or vertically, depending on the orientation of the graph.

bar plot1

Bar Graphs in Matplotlib

我们可以使用 bar() 函数在 Matplotlib 中创建条形图。我们可以指定条形的类别或位置及其对应的高度。要自定义图表,我们可以使用颜色、标签和标题等其他选项。

We can create a bar graph in Matplotlib using the bar() function. We can specify the categories or positions for the bars along with their corresponding heights. To customize the graph, we can use additional options like colors, labels, and titles.

The bar() Function

bar() 函数用于创建条形图。它需要两个主要参数:即 x 轴上的条形位置和条形的高度。

The bar() function is used to create bar graphs. It takes two main parameters: the positions of the bars on the x-axis and the heights of the bars.

以下是 Matplotlib 中 bar() 函数的语法:

Following is the syntax of bar() function in Matplotlib −

Syntax

plt.bar(x, height, width=0.8, align='center', color=None, label=None)

其中,

Where,

  1. x is the positions of the bars on the x-axis.

  2. height is the heights of the bars.

  3. width (optional) is the width of the bars. Default is 0.8.

  4. align (optional) is alignment of the bars. Default is 'center'.

  5. color (optional) is the color of the bars. Default is None, which results in the default color.

  6. label (optional is a label for the legend.

让我们从绘制一个基本的垂直条形图开始。

Let us start by drawing a basic vertical bar graph.

Basic Vertical Bar Graph

在基本的垂直条形图中,我们表示数据,其中每条条形或列对应不同的类别,并且我们使用这些条形的高度来指示与该类别关联的值。

In a basic vertical bar graph, we represent data where each bar or column corresponds to different categories, and we use the heights of these bars to indicate the values associated with that category.

Example

在以下示例中,我们有三个类别(“类别 A”、“类别 B”、“类别 C”),其对应的值为 (15, 24, 30)。然后,我们将使用 plt.bar() 函数创建垂直条形图,其中每条条形表示其各自类别的值:

In the following example, we have three categories ('Category A', 'Category B', 'Category C') with corresponding values (15, 24, 30). We are then using the plt.bar() function to create a vertical bar graph, where each bar represents the value of its respective category −

import matplotlib.pyplot as plt
categories = ['Category A', 'Category B', 'Category C']
values = [15, 24, 30]

plt.bar(categories, values, color='skyblue')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Basic Vertical Bar Graph')
plt.show()

执行上面的代码后,我们得到以下输出: -

After executing the above code, we get the following output −

bar plot2

Horizontal Bar Graph

在水平条形图中,我们通过沿着水平轴(x 轴)水平绘制条形来表示数据。在这种类型的图表中,我们将条形的长度与它们所代表的值关联,并且我们会沿着垂直轴(y 轴)显示类别。

In a horizontal bar graph, we represent data by plotting bars horizontally along a horizontal axis (x-axis). In this type of graph, we associate the lengths of the bars with the values they represent, and we display the categories along the vertical axis (y-axis).

Example

在这里,我们提供了三个类别(“类别 X”、“类别 Y”、“类别 Z”),其对应的值为 (40, 28, 35)。然后,我们将使用 barh() 函数创建水平条形图,其中根据其值的差异,每条条形水平延伸。我们还通过将 color 参数传给函数自定义每个条形颜色:

In here, we are providing three categories ('Category X', 'Category Y', 'Category Z') with corresponding values (40, 28, 35). We are then using the barh() function to create a horizontal bar graph, where each bar extends horizontally based on its value. We are also customizing the color of each bar by passing the color argument to the function −

import matplotlib.pyplot as plt

categories = ['Category X', 'Category Y', 'Category Z']
values = [40, 28, 35]

plt.barh(categories, values, color=['green', 'orange', 'blue'])
plt.xlabel('Values')
plt.ylabel('Categories')
plt.title('Horizontal Bar Graph with Color Customization')
plt.show()

以下是上面代码的输出: -

Following is the output of the above code −

bar plot3

Grouped Bar Graph

在分组条形图,我们堆叠多个垂直条形彼此相邻,用于不同的分类。当我们需要在不同组内比较同一子类的值时,它很有用。

In a grouped bar graph, we stack multiple vertical bars next to each other for different categories. It is useful when you want to compare values for the same subcategories across different groups.

Example

现在,我们提供三个分类('分类 A', '分类 B', '分类 C')和两个不同组的值(组 1 和组 2)。我们然后两次使用 bar() 函数,分别针对每一组,为每一分类并排放置条形 -

Now, we are providing three categories ('Category A', 'Category B', 'Category C') with values for two different groups (Group 1 and Group 2). We are then using the bar() function twice, once for each group, and positioning the bars side by side for each category −

import matplotlib.pyplot as plt
import numpy as np

# Defining categories and their corresponding values for two groups
categories = ['Category A', 'Category B', 'Category C']
values1 = [15, 24, 30]
values2 = [20, 18, 25]

# Setting the width of the bars
bar_width = 0.35
# Calculating bar positions for both groups
bar_positions1 = np.arange(len(categories))
bar_positions2 = bar_positions1 + bar_width

# Creating the first set of bars (Group 1)
plt.bar(bar_positions1, values1, width=bar_width, label='Group 1', color='skyblue')
# Create the second set of bars (Group 2) next to the first set
plt.bar(bar_positions2, values2, width=bar_width, label='Group 2', color='orange')

# Adding labels to the axes
plt.xlabel('Categories')
plt.ylabel('Values')

# Adding a title to the graph
plt.title('Grouped Bar Graph')

# Displaying a legend to identify the groups
plt.legend()

# Showing the plot
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

bar plot4

Stacked Bar Graph

在堆叠条形图,我们将一条条形放在另一条的上面。每条条形表示一个分类,每个分类中所有条形的总高度显示了总值。它有助于比较分类中的总值。

In a stacked bar graph, we put one bar on top of another. Each bar represents a category, and the height of the combined bars at each category shows the total value. It is useful for comparing the total values across categories.

Example

在下面的示例中,我们的三个分类('分类 A', '分类 B', '分类 C')和两个不同组的值(组 1 和组 2)。我们使用 bar() 函数两次,但是这一次,组 2 的条形叠放在组 1 的条形。在第二个 bar() 函数中调用的 bottom 参数表示组 2 条形应该在组 1 条形结束的位置开始 -

In the example below, we have three categories ('Category A', 'Category B', 'Category C') with values for two different groups (Group 1 and Group 2). We are using the bar() function twice, but this time, the bars for Group 2 are stacked on top of the bars for Group 1. The bottom parameter called in the second bar() function indicates that Group 2 bars should start where Group 1 bars end −

import matplotlib.pyplot as plt
# Defining categories and values for two groups
categories = ['Category A', 'Category B', 'Category C']
values1 = [15, 24, 30]
values2 = [20, 18, 25]

# Creating the first set of bars (Group 1) without any offset
plt.bar(categories, values1, label='Group 1', color='skyblue')

# Creating the second set of bars (Group 2) plotted with 'bottom' set to the values of Group 1
# This makes Group 2 bars stacked on top of Group 1 bars
plt.bar(categories, values2, bottom=values1, label='Group 2', color='orange')

# Adding labels to the axes
plt.xlabel('Categories')
plt.ylabel('Values')

plt.title('Stacked Bar Graph')
plt.legend()
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

bar plot5

Dynamically Updating a Bar Graph

在 Matplotlib 中,动态更新条形图是指实时不断改变或刷新条形图中显示的数据的过程。

In Matplotlib, dynamically updating a bar graph refers to the process of continuously changing or refreshing the data displayed in the bars of a bar graph in real-time.

此更新可基于外部因素来进行,例如实时数据流、用户交互或基础数据中的变化。

This updating can occur based on external factors such as live data streams, user interactions, or changes in underlying data.

Example

在下面的示例中,我们动态更新 Matplotlib 中的条形图。我们首先创建一个新图形或激活一个已有的图形。接下来,我们使用 bar() 方法为绘制条形指定数据点和颜色。最后,我们使用 FuncAnimation() 函数来给条形高度和表面颜色添加动画 -

In the example below, we dynamically update a bar plot in Matplotlib. We begin by creating a new figure or activating an existing one. Next, we specify the data points and colors for plotting bars using the bar() method. Finally, we use the FuncAnimation() function to animate the bar heights and face colors −

import numpy as np
from matplotlib import animation as animation, pyplot as plt, cm

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()

data = [1, 4, 3, 2, 6, 7, 3]
colors = ['red', 'yellow', 'blue', 'green', 'black']
bars = plt.bar(data, data, facecolor='green', alpha=0.75)

def animate(frame):
   global bars
   index = np.random.randint(1, 7)
   bars[frame].set_height(index)
   bars[frame].set_facecolor(colors[np.random.randint(0, len(colors))])

ani = animation.FuncAnimation(fig, animate, frames=len(data))

plt.show()

获得的输出如下 −

The output obtained is as follows −

bar plot6