在 Matplotlib 中创建堆积条形图
在本文中,我们将学习如何在 Matplotlib 中创建堆叠条形图。让我们讨论一些概念:
- Matplotlib 是一个巨大的Python可视化库,用于数组的 2D 绘图。 Matplotlib 可能是一个基于 NumPy 数组的多平台数据可视化库,旨在与更广泛的 SciPy 堆栈一起计算。
- 条形图或条形图可以是表示知识类别的图形,其中矩形条的长度和高度与它们所代表的值成正比。条形图通常水平或垂直绘制。
- 堆积条形图代表不同组的最高值。条形图的峰值取决于各组结果的混合高度。它从最低点到价值,而不是从零到价值。
方法:
- 导入库 (Matplotlib)
- 导入/创建数据。
- 以堆叠方式绘制条形图。
示例 1:(简单堆积条形图)
Python3
# importing package
import matplotlib.pyplot as plt
# create data
x = ['A', 'B', 'C', 'D']
y1 = [10, 20, 10, 30]
y2 = [20, 25, 15, 25]
# plot bars in stack manner
plt.bar(x, y1, color='r')
plt.bar(x, y2, bottom=y1, color='b')
plt.show()
Python3
# importing package
import matplotlib.pyplot as plt
import numpy as np
# create data
x = ['A', 'B', 'C', 'D']
y1 = np.array([10, 20, 10, 30])
y2 = np.array([20, 25, 15, 25])
y3 = np.array([12, 15, 19, 6])
y4 = np.array([10, 29, 13, 19])
# plot bars in stack manner
plt.bar(x, y1, color='r')
plt.bar(x, y2, bottom=y1, color='b')
plt.bar(x, y3, bottom=y1+y2, color='y')
plt.bar(x, y4, bottom=y1+y2+y3, color='g')
plt.xlabel("Teams")
plt.ylabel("Score")
plt.legend(["Round 1", "Round 2", "Round 3", "Round 4"])
plt.title("Scores by Teams in 4 Rounds")
plt.show()
Python3
# importing package
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# create data
df = pd.DataFrame([['A', 10, 20, 10, 26], ['B', 20, 25, 15, 21], ['C', 12, 15, 19, 6],
['D', 10, 18, 11, 19]],
columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])
# view data
print(df)
# plot data in stack manner of bar type
df.plot(x='Team', kind='bar', stacked=True,
title='Stacked Bar Graph by dataframe')
输出 :
示例 2:(具有 2 个以上数据的堆积条形图)
蟒蛇3
# importing package
import matplotlib.pyplot as plt
import numpy as np
# create data
x = ['A', 'B', 'C', 'D']
y1 = np.array([10, 20, 10, 30])
y2 = np.array([20, 25, 15, 25])
y3 = np.array([12, 15, 19, 6])
y4 = np.array([10, 29, 13, 19])
# plot bars in stack manner
plt.bar(x, y1, color='r')
plt.bar(x, y2, bottom=y1, color='b')
plt.bar(x, y3, bottom=y1+y2, color='y')
plt.bar(x, y4, bottom=y1+y2+y3, color='g')
plt.xlabel("Teams")
plt.ylabel("Score")
plt.legend(["Round 1", "Round 2", "Round 3", "Round 4"])
plt.title("Scores by Teams in 4 Rounds")
plt.show()
输出 :
示例 3:(使用数据框图的堆积条形图)
蟒蛇3
# importing package
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# create data
df = pd.DataFrame([['A', 10, 20, 10, 26], ['B', 20, 25, 15, 21], ['C', 12, 15, 19, 6],
['D', 10, 18, 11, 19]],
columns=['Team', 'Round 1', 'Round 2', 'Round 3', 'Round 4'])
# view data
print(df)
# plot data in stack manner of bar type
df.plot(x='Team', kind='bar', stacked=True,
title='Stacked Bar Graph by dataframe')
输出 :
Team Round 1 Round 2 Round 3 Round 4
0 A 10 20 10 26
1 B 20 25 15 21
2 C 12 15 19 6
3 D 10 18 11 19