利用Python绘制柱形图或堆积柱形图

本文所运用到的编程工具为Jupyter Notebook

柱形图的绘制

具体编辑代码如下:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(5)
y1 = np.array([10, 8, 7, 11, 13])

# 柱形的宽度
bar_width = 0.3

# 绘制柱形图
plt.bar(x, y1, tick_label=['J', 'e', 's', '0', 'n'], width=bar_width)
plt.show()

运行结果:

利用Python绘制柱形图或堆积柱形图_第1张图片

多组数据柱形图的绘制

具体编辑代码如下:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(5)
y1 = np.array([10, 8, 7, 11, 13])
y2 = np.array([9, 6, 5, 10, 12])

# 柱形的宽度
bar_width = 0.3

# 根据多组数据绘制柱形图
plt.bar(x, y1, tick_label=['J', 'e', 's', '0', 'n'], width=bar_width)
plt.bar(x + bar_width, y2, width=bar_width)

plt.show()

结果所示:

 利用Python绘制柱形图或堆积柱形图_第2张图片

堆积柱形图的绘制

具体编辑代码如下:

​
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(5)
y1 = np.array([10, 8, 7, 11, 13])
y2 = np.array([9, 6, 5, 10, 12])

# 柱形的宽度
bar_width = 0.3

# 绘制堆积柱形图
plt.bar(x, y1, tick_label=['J', 'e', 's', '0', 'n'], width=bar_width)
plt.bar(x, y2, bottom=y1, width=bar_width)

plt.show()

​

结果如图:

利用Python绘制柱形图或堆积柱形图_第3张图片

如若遇到添加误差棒的题目在堆积面积图代码下加入如下代码:

# 偏差数据
error = [2, 1, 2.5, 2, 1.5]

# 绘制带有误差棒的柱形图

plt.bar(x, y1, tick_label=['1', '2', '3', '4', '5'], width=bar_width)
plt.bar(x, y1, bottom=y1, width=bar_width, yerr=error)

plt.show()

利用Python绘制柱形图或堆积柱形图_第4张图片

 

你可能感兴趣的:(python,matplotlib,开发语言)