柱状图/条形图是常见的图形类型,可使用bar()方法绘制。

示例

# 导入numpy库与matplotlib.pyplot库
import numpy as np
import matplotlib.pyplot as plt

# 柱状图条目
divisions = ["Div-A", "Div-B", "Div-C", "Div-D", "Div-E"]
# 柱状图条目的值
divisions_average_marks = [70, 82, 73, 65, 68]

# 绘制图形
plt.bar(divisions, divisions_average_marks, color="green")

# 设置标题
plt.title("Bar Graph")
# 设置x轴标签
plt.xlabel("Divisions")
# 设置y轴标签
plt.ylabel("Marks")

# 显示
plt.show()

输出

示例

# 导入numpy库与matplotlib.pyplot库
import numpy as np
import matplotlib.pyplot as plt

# 柱状图条目
divisions = ["Div-A", "Div-B", "Div-C", "Div-D", "Div-E"]
# 柱状图条目的值
divisions_average_marks = [70, 82, 73, 65, 68]
boys_average_marks = [68, 67, 77, 61, 70]

index = np.arange(5)
width = 0.30

# 绘制图形
plt.bar(index, divisions_average_marks, width, color="green", label="Division Marks")
plt.bar(index + width, boys_average_marks, width, color="red", label="Boys Marks")

# 设置标题
plt.title("Bar Graph")
# 设置x轴标签
plt.xlabel("Divisions")
# 设置y轴标签
plt.ylabel("Marks")
# 设置 x 轴刻度
plt.xticks(index + width/2, divisions)

# 设置图例
plt.legend(loc='best')

# 显示
plt.show()

输出

示例

# 导入numpy库与matplotlib.pyplot库
import numpy as np
import matplotlib.pyplot as plt

# 柱状图条目
divisions = ["Div-A", "Div-B", "Div-C", "Div-D", "Div-E"]
# 柱状图条目的值
boys_average_marks = [68, 67, 77, 61, 70]
girls_average_marks = [72, 97,69, 69, 66]

index = np.arange(5)
width = 0.30

# 绘制图形
plt.bar(index, boys_average_marks, width, color="red", label="Boys Marks")
plt.bar(index, girls_average_marks, width, color="blue", label="Girls Marks", bottom=boys_average_marks)

# 设置标题
plt.title("Bar Graph")
# 设置x轴标签
plt.xlabel("Divisions")
# 设置y轴标签
plt.ylabel("Marks")
# 设置 x 轴刻度
plt.xticks(index, divisions)

# 设置图例
plt.legend(loc='best')

# 显示
plt.show()

输出

12-28 19:52