Matplotlib 创建分组条形图

Matplotlib 创建分组条形图

Matplotlib是Python中最常用的数据可视化库之一。它提供了丰富的可视化工具,能够让我们灵活控制数据图形的各种细节。在这里,我们将介绍如何使用Matplotlib创建一个分组条形图。

首先,我们需要准备我们的数据。在这里,我们使用Pandas来准备数据。我们将创建一个数据框,其中包含多个组的数据,每组有两个变量。我们使用随机数生成数据,如下所示:

import pandas as pd
import numpy as np

# Create a data frame with random data
df = pd.DataFrame({
    'group': ['A', 'B', 'C', 'D', 'E'],
    'variable_1': np.random.randint(10, 50, 5),
    'variable_2': np.random.randint(20, 60, 5)})

print(df)
Python

这将输出以下数据框:

  group  variable_1  variable_2
0     A          40          48
1     B          25          49
2     C          22          39
3     D          31          26
4     E          42          54
Python

我们的数据现在已经准备好了。我们将使用Matplotlib来创建一个分组条形图。代码如下所示:

import matplotlib.pyplot as plt

# Set the font size and style of all plots to be consistent
plt.rcParams.update({'font.size': 22})

# Set the style of the plot
plt.style.use('ggplot')

# Create the figure and axis objects
fig, ax = plt.subplots(figsize=(10, 8))

# Set the positions of the bars on the x-axis
x_pos = np.arange(len(df['group']))

# Set the width of the bars
width = 0.35

# Plot the first variable
ax.bar(x_pos - width/2, df['variable_1'], width=width, label='Variable 1')

# Plot the second variable
ax.bar(x_pos + width/2, df['variable_2'], width=width, label='Variable 2')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Value')
ax.set_xlabel('Group')
ax.set_xticks(x_pos)
ax.set_xticklabels(df['group'])
ax.legend()

# Show the plot
plt.show()
Python

这个图形显示了每个组的两个变量的条形图。我们可以看到,使用Matplotlib很容易创建分组条形图。

阅读更多:Matplotlib 教程

总结

在这篇文章中,我们介绍了如何使用Matplotlib和Pandas创建一个分组条形图。我们使用Pandas生成了一个数据框,并使用Matplotlib创建了一个简单而漂亮的图形。Matplotlib是一个功能强大的可视化工具,它可以让我们轻松地控制条形图的各个方面。在实际应用中,我们可以使用分组条形图来比较不同组的变量。我希望这篇文章对你有所帮助,可以让你更好地了解Matplotlib和Pandas的使用。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册